標籤:內容 原型 logs 輸出 str cto manually one prot
定義Foo,Bar
其中,Bar繼承Foo
a是Bar的執行個體,包含有Foo和Bar的函數和屬性:
function Foo(name) { this.name = name;}Foo.prototype.myName = function() { return this.name;};function Bar(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 ); //核心代碼// Beware! Now `Bar.prototype.constructor` is gone,// and might need to be manually "fixed" if you‘re// in the habit of relying on such properties!Bar.prototype.myLabel = function() { return this.label;};var a = new Bar( "a", "obj a" );a.myName(); // "a"a.myLabel(); // "obj a"
其中核心代碼為
Bar.prototype = Object.create( Foo.prototype );
我們把這行代碼換為以下幾種寫法,仍可使輸出不變,但內部實現則完全不同了。
1、Bar.prototype = Foo.prototype;
推薦指數:★
評價:執行Bar.prototype.myLabel = ...的指派陳述式會直接修改Foo.prototype對象本身,還不如不要Bar只用Foo
//第1種Bar.prototype = Foo.prototype;a; //輸出如下Bar {name: "a", label: "obj a"}a.__proto__; //輸出如下Object {myName: function, myLabel: function, constructor: function}a.__proto__.__proto__; //輸出如下Object {method: function, __defineGetter__: function, __defineSetter__: function, hasOwnProperty: function, __lookupGetter__: function…}
2、Bar.prototype = new Foo();
推薦指數:★
評價:Foo函數的內容有可能產生副作用,他的操作將直接影響Bar()的後代,後果不堪設想。如下面的undefined
//第2種Bar.prototype = new Foo();a; //輸出如下Bar {name: "a", label: "obj a"}a.__proto__; //輸出如下Foo {name: undefined, myLabel: function}a.__proto__.__proto__; //輸出如下Object {myName: function, constructor: function}
3、Object.setPrototypeOf(Bar.prototype,Foo.prototype);
推薦指數:★★★★★
評價:完美,Bar的建構函式沒變
Bar.prototype.constructor
function Bar(name,label) {
Foo.call( this, name );
this.label = label;
}
//第3種Object.setPrototypeOf(Bar.prototype,Foo.prototype);a; //輸出如下Bar {name: "a", label: "obj a"}a.__proto__; //輸出如下Foo {myLabel: function, constructor: function}a.__proto__.__proto__; //輸出如下Object {myName: function, constructor: function}
4、Bar.prototype = Object.create(Foo.prototype);
推薦指數:★★★★
評價: Bar.prototype本身的constructor丟失了,去原型找,導致
Bar.prototype.constructor
function Foo(name) {
this.name = name;
}
//原文Bar.prototype = Object.create(Foo.prototype);a; //輸出如下Bar {name: "a", label: "obj a"}a.__proto__; //輸出如下Foo {myLabel: function}a.__proto__.__proto__; //輸出如下Object {myName: function, constructor: function}
JavaScript的幾種(原型)繼承