function Foo(name) { this.name = name; } Foo.prototype.myName = function () { return this.name; } var a = new Foo('a'); a.myName(); // 'a'
There are too many ways to simulate the behavior of classes in JS, but if there is no "inheritance" mechanism, the class in JS is just an empty shelf. a can inherit Foo.prototype and access Foo.prototype's myName () function. The mechanism commonly referred to as prototypal inheritance.
function Foo(name) { this.name = name; } Foo.prototype.myName = function () { return this.name; } function Bar(name, label) { Foo.call(this, name); this.label = label } // We create a new Bar.prototype object and associate it with Foo.prototype Bar.prototype = Object.create (Foo.prototype); // Note that there is no Bar.prototype.constructor now /// If you need this property, you may need to fix it manually Bar.prototype.myLabel = function () { return this .label } var a = new Bar ('a', 'obj a' ); a.myName(); // 'a' a.myLabel(); // 'obj a'
The core part of this code is Bar.prototype = Object.create (Foo.prototype); Create a new Bar.prototype object and associate it with Foo.prototype.
// Not the same mechanism as you want Bar.prototype = Foo.prototype; // Basically meet your needs, but may have some side effects: Bar.prototype = new Foo ();
Bar.prototype = Foo.prototype does not create a new object associated with Bar.prototype, it just lets Bar.prototype directly reference Foo.prototype, so the assignment statement directly modifies the Foo.prototype object itself.
Bar.prototype = new Foo () does create a new object associated with Bar.prototype. But it is called with a constructor. If the function Foo has some side effects, it will affect the descendants of Bar (), and the consequences are unbearable.
The only disadvantage of Object.create is that you need to create a new object and then discard the old object. You cannot directly modify the existing default object.
// Before ES6, you need to abandon the default Bar.prototype Bar.prototype = Object.create (Foo.prototype); // From ES6, you can directly modify the existing Bar.prototype Object.setPrototypeOf (Bar.prototype, Foo.prototype);
If you ignore the slight performance loss caused by Object.create (abandoned objects need to be garbage collected), it is actually shorter and more readable than ES6 and later methods. In any case, these are two different syntaxes.