I recently stumbled upon the Object.create()
method in JavaScript, and am trying to deduce how it is different from creating a new instance of an object with new SomeFunction()
, and when you would want to use one over the other.
Consider the following example:
var test = { val: 1, func: function() { return this.val; } }; var testA = Object.create(test); testA.val = 2; console.log(test.func()); // 1 console.log(testA.func()); // 2 console.log('other test'); var otherTest = function() { this.val = 1; this.func = function() { return this.val; }; }; var otherTestA = new otherTest(); var otherTestB = new otherTest(); otherTestB.val = 2; console.log(otherTestA.val); // 1 console.log(otherTestB.val); // 2 console.log(otherTestA.func()); // 1 console.log(otherTestB.func()); // 2
Notice that the same behaviour is observed in both cases. It seems to me that the primary differences between these two scenarios are:
Object.create()
actually forms the prototype of the new object, whereas in the new Function()
from the declared properties/functions do not form the prototype. Object.create()
syntax as you would with the functional syntax. This is logical given the lexical (vs block) type scope of JavaScript.Are the above statements correct? And am I missing something? When would you use one over the other?
EDIT: link to jsfiddle version of above code sample: http://jsfiddle.net/rZfYL/
The major difference is that Object. Create returns the new object while the constructor function return the constructor of the object or the object. This is due to the important difference that new actually runs constructor code, whereas Object. create will not execute the constructor code.
In the Rails convention new is used with the HTTP verb GET and create is used with POST . Say you are creating a blog and you have a model object called post . In the controller the new method will send a new post object to the view (a form).
If you are more concerned with having a set prototype but the object itself is more static than not, Object. create would be a better option as it is cleaner and doesn't mess with the proto-chain in unexpected ways as the new operator does.
create() method creates a new object, using an existing object as the prototype of the newly created object.
Very simply said, new X
is Object.create(X.prototype)
with additionally running the constructor
function. (And giving the constructor
the chance to return
the actual object that should be the result of the expression instead of this
.)
That’s it. :)
The rest of the answers are just confusing, because apparently nobody else reads the definition of new either. ;)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With