JavaScript的幾種(原型)繼承

來源:互聯網
上載者:User

標籤:內容   原型   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的幾種(原型)繼承

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.