Pacerier
Pacerier

Reputation: 89583

What does the JavaScript "Object" function do?

What does the Object function in JavaScript do?

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

Upvotes: 3

Views: 159

Answers (5)

wosis
wosis

Reputation: 1219

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>

Upvotes: 1

wong2
wong2

Reputation: 35710

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

Upvotes: 0

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).

Upvotes: 2

Lekensteyn
Lekensteyn

Reputation: 66375

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.

Upvotes: 4

Alex
Alex

Reputation: 7374

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

Upvotes: 0

Related Questions