Understanding the difference between Object.create() and new SomeFunction()

后端 未结 11 2614
失恋的感觉
失恋的感觉 2020-11-22 05:05

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

11条回答
  •  孤城傲影
    2020-11-22 05:39

    Let me try to explain (more on Blog) :

    1. When you write Car constructor var Car = function(){}, this is how things are internally: A diagram of prototypal chains when creating javascript objects We have one {prototype} hidden link to Function.prototype which is not accessible and one prototype link to Car.prototype which is accessible and has an actual constructor of Car. Both Function.prototype and Car.prototype have hidden links to Object.prototype.
    2. When we want to create two equivalent objects by using the new operator and create method then we have to do it like this: Honda = new Car(); and Maruti = Object.create(Car.prototype).A diagram of prototypal chains for differing object creation methods What is happening?

      Honda = new Car(); — When you create an object like this then hidden {prototype} property is pointed to Car.prototype. So here, the {prototype} of the Honda object will always be Car.prototype — we don't have any option to change the {prototype} property of the object. What if I want to change the prototype of our newly created object?
      Maruti = Object.create(Car.prototype) — When you create an object like this you have an extra option to choose your object's {prototype} property. If you want Car.prototype as the {prototype} then pass it as a parameter in the function. If you don't want any {prototype} for your object then you can pass null like this: Maruti = Object.create(null).

    Conclusion — By using the method Object.create you have the freedom to choose your object {prototype} property. In new Car();, you don't have that freedom.

    Preferred way in OO JavaScript :

    Suppose we have two objects a and b.

    var a = new Object();
    var b = new Object();
    

    Now, suppose a has some methods which b also wants to access. For that, we require object inheritance (a should be the prototype of b only if we want access to those methods). If we check the prototypes of a and b then we will find out that they share the prototype Object.prototype.

    Object.prototype.isPrototypeOf(b); //true
    a.isPrototypeOf(b); //false (the problem comes into the picture here).
    

    Problem — we want object a as the prototype of b, but here we created object b with the prototype Object.prototype. Solution — ECMAScript 5 introduced Object.create(), to achieve such inheritance easily. If we create object b like this:

    var b = Object.create(a);
    

    then,

    a.isPrototypeOf(b);// true (problem solved, you included object a in the prototype chain of object b.)
    

    So, if you are doing object oriented scripting then Object.create() is very useful for inheritance.

提交回复
热议问题