Define Foo,bar
Where Bar inherits Foo
A is an instance of bar that contains the functions and properties of Foo and bar:
functionFoo (name) { This. Name =name;} Foo.prototype.myName=function() { return This. Name;};functionBar (Name,label) {Foo.call ( This, name); This. Label =label;}//Here , we make a new ' Bar.prototype '//linked to ' Foo.prototype 'Bar.prototype = object.create (Foo.prototype);//Core Code//beware! Now ' Bar.prototype.constructor ' is gone,//And might need to being manually "fixed" If you ' re//In the habit of relying on such properties!Bar.prototype.myLabel=function() { return This. Label;};varA =NewBar ("A", "obj a"); A.myname (); //"a"A.mylabel ();//"obj a"
Where the core code is
Bar.prototype = Object.create (Foo.prototype);
We can still make the output unchanged by changing this line of code to the following, but the internal implementation is completely different.
1, bar.prototype = Foo.prototype;
Recommended Index: ★
Rating: Performing Bar.prototype.myLabel = ... Assignment statement will directly modify the Foo.prototype object itself, rather than the bar only with Foo
//1th TypeBar.prototype =Foo.prototype;a;//The output is as followsBar {name: ' A ', Label: ' obj a '}a.__proto__; //The output is as followsObject {myName:function, MyLabel:function, constructor:function}a.__proto__.__proto__; //The output is as followsObject {method:function, __definegetter__:function, __definesetter__:function, hasOwnProperty:function, __lookupgetter__:function...}
2, Bar.prototype = new Foo ();
Recommended Index: ★
Evaluation: The contents of the Foo function are likely to have side effects, and his operations will directly affect the offspring of Bar (), with disastrous consequences. As the following undefined
// 2nd Type New // output The following Bar {name: "A", Label: "obj a"// outputs the following function // output The following functionfunction}
3, object.setprototypeof (Bar.prototype,foo.prototype);
Recommendation Index: ★★★★★
Rating: Perfect, bar's constructor has not changed
Bar.prototype.constructor
function Bar (Name,label) {
Foo.call (this, name);
This.label = label;
}
// 3rd Type // output The following Bar {name: "A", Label: "obj a"// outputs the following function function // output The following functionfunction}
4, Bar.prototype = Object.create (Foo.prototype);
Recommendation Index: ★★★★
Evaluation: Bar.prototype itself constructor lost, go to prototype find, cause
Bar.prototype.constructor
function Foo (name) {
THIS.name = name;
}
// Original Bar.prototype =// output follows Bar {name: "A", Label: "Obj a"// output as follows function// output as functionfunction}
Several (prototype) inheritance of JavaScript