Performance. What does Object (obj) do?

Snippet from underscore.js for test object

_.isObject = function(obj) { return obj === Object(obj); }; 

What exactly does this do, what causes it to check the type?

jsperf shows that it is faster than a regular check, therefore it is used.

+4
source share
3 answers

What does Object (obj) do?

Read the EcmaScript specification on the Object Constructor called as a function and abstract ToObject .

What exactly does this do, what causes it to check the type?

Object(obj) will only cause the object to be strictly equal ( === ) to obj (i.e. the same reference as the input) when the input was not a primitive value ( null , booleans, strings, numbers, undefined ), that is, an EcmaScript object (including instances of String / Boolean / Number / Array, functions, other objects).

+1
source

The object constructor creates an object wrapper for a given value. If the value is null or undefined, it will create and return an empty object, otherwise it will return an object of the type corresponding to the given value.

A source

+5
source

I cannot find the relevant documentation, but it seems that the Object function returns a new object that wraps the passed value or returns an argument if it is already an object; otherwise, the test === always returned false.

 Object(5) === 5 // false, Object(5) creates Number object Object(null) === null // false, Object(null) creates an empty object var foo = { prop: 'value' }; Object(foo) === foo // true!? Argument is not wrapped 

This behavior seems to work to check if the value is an object.

Update

It looks like this is in the specification :

When the Object function is called with no arguments or with a single argument value, the following steps are taken:
1. If the value is null, undefined or not specified, create and return a new Object in the same way as if the standard built-in Object constructor was called with the same arguments (15.2.2.1).
2. Return ToObject (value).

And the result of ToObject - this input object is also defined in the specification .

+1
source

All Articles