javascript原型繼承中兩種方法的簡介和對比

來源:互聯網
上載者:User

在實際的項目中,我們通常都是用建構函式來建立一個對象,再將一些常用的方法添加到其原型對象上。最後要麼直接執行個體化該對象,要麼將它作為父類,再申明一個對象,繼承該父類。

而在繼承的時候有兩種常用方式,今天我們就來稍作探討

//父類 function Person(name){    this.name = name;};     // 子類 function Student(sex){  Person.apply(this,arguments); //繼承父類的建構函式  this.sex=sex; };

1,繼承Prototype:

1  Student.prototype = Person.prototype; //執行完此句時,Student.prototype.constructor 指向的是Person,為什麼了?因為Person.prototype.constructor指向Person,對象的賦值實質上是引用賦值,所以Student.prototype.constructor也指向Person

2  Student.prototype.constructor = Student;  //  將Student.prototype.constructor 指回Person

用Person的原型對象來覆蓋Student的原型對象;前面說到對象的賦值實質上是引用賦值,所以如果Student.prototype上的任何修改都會體現到Person.prototype中,即子類會影響父類。

查看本欄目更多精彩內容:http://www.bianceng.cnhttp://www.bianceng.cn/webkf/script/

看下面:

1 Student.prototype.add=function(){alert("add")};

2 Person.prototype.add();//彈出add

2,繼承執行個體:

1 Student.prototype = new Person();  //如果此處不傳遞參數,可以不寫();即直接寫成 new Person;

2 Student.prototype.constructor = Student;

用Person的執行個體來覆蓋Student的原型對象;建立了執行個體,比起前面那種,顯示是浪費記憶體了,不過這同時也解決了上面那種方法的缺點,即此時Student.prototype上的任何修改不會體現到Person.prototype中,即子類不會影響父類。

3,利用控對象來組合1和2的優點,去掉缺點

1 var  F = function(){};

2 F.prototype = Person.prototype;

3 Student.prototype  = new F();

4 Student.prototype.constructor  = Student;

F是個Null 物件,上面只有些原型方法,執行個體化時記憶體佔用較少,同時也隔離開了子類對父類的影響。

作者:cnblogs 溫伯

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.