I've been playing with and studying the prototype chain in Javascript and this subject got me wondering... is there a common name or term to refer to the object that everything else in the end of the prototype chain?
I'm writing a markdown file on a GitHub repo of mine and there I refer to it as the "God" object. But I'm quite unsure about how this object behaves.
Could I, for example, change the reference on one specific type of Object (lets say, Dog object) to have its own "God", or will I be stuck with this one single "God" object?
The "God" object you're referring to is Object.prototype.
console.log({}.__proto__ === Object.prototype);
console.log({}.__proto__.__proto__);
If you want to create your own "God" object, use Object.create(null)
var obj = Object.create(null);
console.log(obj.__proto__);
It is commonly used when creating a lookup table, so as to avoid any name conflicts with fields in the prototype, such as toString.
function Map() {
var table = Object.create(null);
return {
put: function(key, val) {
table[key] = val;
},
get: function(key) {
return table[key];
}
};
}
var map = new Map();
console.log(map.get('toString'));
map.put('toString', 'test');
console.log(map.get('toString'));
What is the difference between this constructor-based syntax for creating an object:
person = new Object()
...and this literal syntax:
person = {
property1 : "Hello"
};
It appears that both do the same thing, although JSLint prefers you use object literal notation.
Which one is better and why?
There is no difference for a simple object without methods as in your example.
However, there is a big difference when you start adding methods to your object.
Literal way:
function Obj( prop ) {
return {
p : prop,
sayHello : function(){ alert(this.p); },
};
}
Prototype way:
function Obj( prop ) {
this.p = prop;
}
Obj.prototype.sayHello = function(){alert(this.p);};
Both ways allow creation of instances of Obj like this:
var foo = new Obj( "hello" );
However, with the literal way, you carry a copy of the sayHello method within each instance of your objects. Whereas, with the prototype way, the method is defined in the object prototype and shared between all object instances.
If you have a lot of objects or a lot of methods, the literal way can lead to quite big memory waste.
They both do the same thing (unless someone's done something unusual), other than that your second one creates an object and adds a property to it. But literal notation takes less space in the source code. It's clearly recognizable as to what is happening, so using new Object(), you are really just typing more and (in theory, if not optimized out by the JavaScript engine) doing an unnecessary function call.
These
person = new Object() /*You should put a semicolon here too.
It's not required, but it is good practice.*/
-or-
person = {
property1 : "Hello"
};
technically do not do the same thing. The first just creates an object. The second creates one and assigns a property. For the first one to be the same you then need a second step to create and assign the property.
The "something unusual" that someone could do would be to shadow or assign to the default Object global:
// Don't do this
Object = 23;
In that highly-unusual case, new Object will fail but {} will work.
In practice, there's never a reason to use new Object rather than {} (unless you've done that very unusual thing).
In JavaScript, we can declare a new empty object in two ways:
var obj1 = new Object();
var obj2 = {};
I have found nothing to suggest that there is any significant difference these two with regard to how they operate behind the scenes (please correct me if i am wrong – I would love to know). However, the second method (using the object literal notation) offers a few advantages.
It is shorter (10 characters to be precise)
It is easier, and more structured to create objects on the fly
It doesn’t matter if some buffoon has inadvertently overridden Object
Consider a new object that contains the members Name and TelNo. Using the new Object() convention, we can create it like this:
var obj1 = new Object();
obj1.Name = "A Person";
obj1.TelNo = "12345";
The Expando Properties feature of JavaScript allows us to create new members this way on the fly, and we achieve what were intending. However, this way isn’t very structured or encapsulated. What if we wanted to specify the members upon creation, without having to rely on expando properties and assignment post-creation?
This is where the object literal notation can help:
var obj1 = {Name:"A Person",TelNo="12345"};
Here we have achieved the same effect in one line of code and significantly fewer characters.
A further discussion the object construction methods above can be found at: JavaScript and Object Oriented Programming (OOP).
And finally, what of the idiot who overrode Object? Did you think it wasn’t possible? Well, this JSFiddle proves otherwise. Using the object literal notation prevents us from falling foul of this buffoonery.
(From http://www.jameswiseman.com/blog/2011/01/19/jslint-messages-use-the-object-literal-notation/)
On my machine using Node.js, I ran the following:
console.log('Testing Array:');
console.time('using[]');
for(var i=0; i<200000000; i++){var arr = []};
console.timeEnd('using[]');
console.time('using new');
for(var i=0; i<200000000; i++){var arr = new Array};
console.timeEnd('using new');
console.log('Testing Object:');
console.time('using{}');
for(var i=0; i<200000000; i++){var obj = {}};
console.timeEnd('using{}');
console.time('using new');
for(var i=0; i<200000000; i++){var obj = new Object};
console.timeEnd('using new');
Note, this is an extension of what is found here: Why is arr = [] faster than arr = new Array?
my output was the following:
Testing Array:
using[]: 1091ms
using new: 2286ms
Testing Object:
using{}: 870ms
using new: 5637ms
so clearly {} and [] are faster than using new for creating empty objects/arrays.
Everyone here is talking about the similarities of the two. I am gonna point out the differences.
Using new Object() allows you to pass another object. The obvious outcome is that the newly created object will be set to the same reference. Here is a sample code:
var obj1 = new Object();
obj1.a = 1;
var obj2 = new Object(obj1);
obj2.a // 1
The usage is not limited to objects as in OOP objects. Other types could be passed to it too. The function will set the type accordingly. For example if we pass integer 1 to it, an object of type number will be created for us.
var obj = new Object(1);
typeof obj // "number"
The object created using the above method (new Object(1)) would be converted to object type if a property is added to it.
var obj = new Object(1);
typeof obj // "number"
obj.a = 2;
typeof obj // "object"
If the object is a copy of a child class of object, we could add the property without the type conversion.
var obj = new Object("foo");
typeof obj // "object"
obj === "foo" // true
obj.a = 1;
obj === "foo" // true
obj.a // 1
var str = "foo";
str.a = 1;
str.a // undefined
Actually, there are several ways to create objects in JavaScript. When you just want to create an object there's no benefit of creating "constructor-based" objects using "new" operator. It's same as creating an object using "object literal" syntax. But "constructor-based" objects created with "new" operator comes to incredible use when you are thinking about "prototypal inheritance". You cannot maintain inheritance chain with objects created with literal syntax. But you can create a constructor function, attach properties and methods to its prototype. Then if you assign this constructor function to any variable using "new" operator, it will return an object which will have access to all of the methods and properties attached with the prototype of that constructor function.
Here is an example of creating an object using constructor function (see code explanation at the bottom):
function Person(firstname, lastname) {
this.firstname = firstname;
this.lastname = lastname;
}
Person.prototype.fullname = function() {
console.log(this.firstname + ' ' + this.lastname);
}
var zubaer = new Person('Zubaer', 'Ahammed');
var john = new Person('John', 'Doe');
zubaer.fullname();
john.fullname();
Now, you can create as many objects as you want by instantiating Person construction function and all of them will inherit fullname() from it.
Note:
"this" keyword will refer to an empty object within a constructor function and whenever you create a new object from Person using "new" operator it will automatically return an object containing all of the properties and methods attached with the "this" keyword. And these object will for sure inherit the methods and properties attached with the prototype of the Person constructor function (which is the main advantage of this approach).
By the way, if you wanted to obtain the same functionality with "object literal" syntax, you would have to create fullname() on all of the objects like below:
var zubaer = {
firstname: 'Zubaer',
lastname: 'Ahammed',
fullname: function() {
console.log(this.firstname + ' ' + this.lastname);
}
};
var john= {
firstname: 'John',
lastname: 'Doe',
fullname: function() {
console.log(this.firstname + ' ' + this.lastname);
}
};
zubaer.fullname();
john.fullname();
At last, if you now ask why should I use constructor function approach instead of object literal approach:
*** Prototypal inheritance allows a simple chain of inheritance which can be immensely useful and powerful.
*** It saves memory by inheriting common methods and properties defined in constructor functions prototype. Otherwise, you would have to copy them over and over again in all of the objects.
I hope this makes sense.
Also, according to some of the O'Really javascript books....(quoted)
Another reason for using literals as opposed to the Object constructor is that there is no scope resolution. Because it’s possible that you have created a local constructor with the same name, the interpreter needs to look up the scope chain from the place you are calling Object() all the way up until it finds the global Object constructor.
2019 Update
I ran the same code as #rjloura on my OSX High Sierra 10.13.6 node version 10.13.0 and these are the results
console.log('Testing Array:');
console.time('using[]');
for(var i=0; i<200000000; i++){var arr = []};
console.timeEnd('using[]');
console.time('using new');
for(var i=0; i<200000000; i++){var arr = new Array};
console.timeEnd('using new');
console.log('Testing Object:');
console.time('using{}');
for(var i=0; i<200000000; i++){var obj = {}};
console.timeEnd('using{}');
console.time('using new');
for(var i=0; i<200000000; i++){var obj = new Object};
console.timeEnd('using new');
Testing Array:
using[]: 117.613ms
using new: 117.168ms
Testing Object:
using{}: 117.205ms
using new: 118.644ms
I have found one difference, for ES6/ES2015. You cannot return an object using the shorthand arrow function syntax, unless you surround the object with new Object().
> [1, 2, 3].map(v => {n: v});
[ undefined, undefined, undefined ]
> [1, 2, 3].map(v => new Object({n: v}));
[ { n: 1 }, { n: 2 }, { n: 3 } ]
This is because the compiler is confused by the {} brackets and thinks n: i is a label: statement construct; the semicolon is optional so it doesn't complain about it.
If you add another property to the object it will finally throw an error.
$ node -e "[1, 2, 3].map(v => {n: v, m: v+1});"
[1, 2, 3].map(v => {n: v, m: v+1});
^
SyntaxError: Unexpected token :
The only time i will use the 'new' keyowrd for object initialization is in inline arrow function:
() => new Object({ key: value})
since the below code is not valid:
() => { key: value} // instead of () => { return { key: value};}
There are a lot of great answers here, but I want to come with my 50 cents.
What all of these answers are missing is a simple analogy which would work for a person who just starts his journey in the programming languages.
Hopefully, I will fill this gap with this analogy:
Object Literal Creation vs Constructor-based Syntax
Feel the difference with a sentence creation.
If I have a sentence "I like cheese", I can tell you clearly and loudly (literally, or verbatim): I like cheese.
This is my literal (word by word) creation of the sentence.
All other ways are some tricky ways of making you to understand of what sentence I created exactly. For example, I tell you:
In my sentence, the subject is "I", the object is "cheese", and the predicate is "to like".
This is another way of YOU to learn without any ambiguities the very same sentence: "I like cheese".
Or,
My sentence has 3 words: the first one is the n-th word in the English dictionary, the the second one is the m-th word in the English dictionary and the last one is the l-th word in the English dictionary.
In this case, you also come to the same result: you know exactly what the sentence is.
You can devise any other methods which would differ from "word-by-word" sentence creation (LITERAL), and which would be INDIRECT (non literal, non verbatim) method of sentence creation.
I think this is the core concept which lays here.
Memory usage is different if you create 10 thousand instances.
new Object() will only keep only one copy while {} will keep 10 thousand copies.
Ok am just going through basics of JavaScript and I was learning objects where I came across this example...
JavaScript
var person = {
firstname : "Smith",
lastname : "Bach"
};
And what we write in PHP is
$person = array(
"firstname"=>"Smith",
"lastname"=>"Bach"
);
So is this the same thing or am making a mistake in understanding the concept?
No, objects are more than that.
Object is indeed a map/dictionary, but additionally every object inherits some of the properties (key-value pairs) from another object. That other object is called prototype.
For example:
var o = {
x: 1
};
console.log(o.x === undefined); // false, obviously
console.log(o.toString === undefined); // false, inherited from prototype
Most commonly a prototype is set by creating an object with a constructor function:
var d = new Date();
console.log(d.hasOwnProperty('getYear')); // false, it's inherited
EDIT:
Here's how the prototype works using constructor functions (it's one of the ways to do OOP in JS):
// constructor function
// starts with capital letter, should be called with new
var Person = function (name, age) {
// set properties of an instance
this.name = name;
this.age = age;
};
// functions to be inherited are in the prototype
Person.prototype.sayHello = function () {
return this.name + ' is ' + this.age + ' old';
};
// new:
// - creates the object
// - sets up inheritance from prototype
// - sets the object as the context of the constructor function call (this)
var p = new Person('Jason', 27);
console.log(p.sayHello());
They are associative arrays, but not just associative arrays. There are functions available from the Object prototype (like .toString()) whose names can collide with property names. Objects can be constructed via other functions and given more inherited properties too. (Note that one thing that plain objects don't have is a .length property to count entries, like array objects have. The term "associative array" is probably not the best one to use for JavaScript objects; they're objects and that should be enough once you're familiar with JavaScript.)
edit — what I mean is this:
var o = {};
alert("toString" in o); // alerts "true"
Thus a newly-created empty object appears to have a property called "toString". The issue with JavaScript is that there's only one property accessor operator (well two, but they're two flavors of the same thing), so there's no way to distinguish between accesses to the array's contents and access to the array's API. (Also, in JavaScript it's really not a good idea to think of them using the word "array", as that means something different in JavaScript — arrays are a type of Object with special properties.)
EcmaScript 5 has mechanisms for defining object properties in such a way as to make them immutable and non-iterable, which helps some. It's still problematic if you want to store a property called "toString" in an object.
I'm pretty new to plain old JavaScript and to JavaScript frameworks (such as Backbone.js, RequireJS, ...). As I was reading and trying to understand some JavaScript files that I got from a project at work (based on JQuery, Backbone and Require), I've encountered some variable declarations such as:
var myVariable = {}, itemList;
Could someone explain to me what the "{}" is?
PS: might be a silly question but it's definitely not that easy Googling for "{}" as keyword...
Thanks in advance.
{} is just the javascript way of defining a collection or object.
In this example, it is filled with an object literal
var apple = {
type: "macintosh",
color: "red",
getInfo: function () {
return this.color + ' ' + this.type + ' apple';
}
}
var featurelessApple = {};
It's an empty Javascript object literal (A shorthand way of creating an object)
var myVariable = {};
is similar to
var myVariable = new Object();
Both expressions will create an empty object.
myVariable is an object literal, or generic object.
For future reference you can easily see this by using the console in your browser. In Chrome
var myVariable = {}
console.log(myVariable);
This will then print out the entire object. In this
Object {}
That's an empty object literal.
Object literals consist in zero or more key/value pairs enclosed in curly braces. In your example, there are zero key/value pairs, so the object does not define any property.
What does assigning a variable to {}, mean? Is that initializing it to a function? I have code in a javascript file that says this
GLGE.Wavefront = function(uid) {
GLGE.Assets.registerAsset(this,uid);
this.multimaterials = [];
this.materials = {}; // <---
this.instances = [];
this.renderCaches = [];
this.queue = [];
};
how is that assignment different from an array? Is it a type of array?
What does assigning a variable to {}, mean?
It is an object literal (with no properties of its own).
Is that initializing it to a function?
No, that would be = function () { }.
how is that assignment different from an array?
An array has a bunch of features not found in a basic object, such as .length and a bundle of methods.
Objects are often used to store arbitrary key/value pairs. Arrays are for ordered values.
This is javascript object notation. Particularly {} means empty object, the same as new Object();. See json.org.
That would be an empty JavaScript object.
Using {} creates an object. You can use the object like a hash-map or similar to how you can use arrays in PHP.
var obj = {};
obj['test'] = 'valuehere';
obj.secondWay = 'secondValue';
and you could access them by calling obj.test and obj['secondWay'].
It's an initialized empty object, eg. an object of no particular type. It serves to provide a definition for this.materials so that the code won't have to check it for null or being defined later.
It does create an empty object.
var myObj = {};
Within an object you can define key/value pairs, e.g.:
myObj.color = 'red';
A value can be a function, too:
myObj.getColor = function() { return this.color };
It's JON (Javascript Object Notation) for creating a new empty object. Almost equal in idea to how you'd normally do Object x = new Object() in java, minus the initialization part...