3

What does the Object function in JavaScript do?

For example, what happens when we do Object(1)?

5 Answers 5

4

It forces something to be an object. I've not seen it being used in this way though.

var num = 1;
var obj = Object(num);
alert(typeof num); //displays "number"
alert(typeof obj): //displays "object"
alert(num + "," + obj); //displays "1,1"

The preferred, faster way to create an empty object on which you can put properties and methods on is by using {}. Three possible ways to create an object:

var emptyObj = {};
var emptyObj = new Object();
var emptyObj = new Object; // Object does not need an argument, so this is valid.
Sign up to request clarification or add additional context in comments.

3 Comments

heys regarding the third example, is it "standard" and widely supported?
@Pacerier: Per "JavaScript: The Definitive Guide", by David Flanagan, 5.10.3: "As a special case, for the new operator only, JavaScript simplifies the grammar by allowing the parentheses to be omitted if there are no arguments in the function call".
@Pacerier: Section 5.2.2 (and 5.2.2.1) from EXCMA 262 specification allows new Object and new Object(). Per 5.2.2: "When Object is called as part of a new expression, it is a constructor that may create an object.". Per 5.2.2.1: "When the Object constructor is called with no arguments or with one argument value, the following steps are taken: [..] 8. Return obj." So, the behavior is the same.
2

From the Mozilla developer site:

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

When called in a non-constructor context, Object behaves identically.

So Object(1) produces an object that behaves similarly to the primitive value 1, but with support for object features like assigning values to properties (Object(1).foo = 2 will work, (1).foo = 2 will not).

Comments

1
var obj = Object("test");

Creates a String "text", it's pretty similar to

var obj2 = "test";

Notice that the type of obj2 is "String" and of obj1 "Object"

Try this:

 <script>
var obj = Object("test");
console.log(obj);
console.log(typeof(obj));
console.log(obj["0"]);

obj2 = "test";
console.log(obj2);
console.log(typeof(obj2));
console.log(obj2["0"]);

</script>

Comments

0

Creates an object http://www.w3schools.com/js/js_objects.asp

Comments

0

Object function is a constructor function, all other types(like Array, String, Number) inheritate it.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.