js中的繼承

來源:互聯網
上載者:User

標籤:可見   prot   push   函數   原型鏈   this   組合   繼承   instance   

實現原型鏈有一種基本模式,其代碼大致如下: function A(){     this.property = true;}A.prototype.getAvalue = function(){  return this.property;   };function B(){     this.property = false;}//繼承了AB.prototype = new A();B.prototype.getBvalue = function(){     return this.property;};var instance = new B();console.log(instance.getBvalue());//true;  借用建構函式 function A(){     this.color = ["red","blue"];} function B(){     // 繼承了A     A.call(this);} var instance1 = new B();instance1.color.push("yellow");console.log(instance1.color);//red,blue,yellow; var instance2 = new B();console.log(instance2.color);//red,blue; 1,傳遞參數相對於原型鏈而言,借用建構函式有一個很大的優勢,既可以在子類型建構函式中向超類型建構函式傳遞參數;如下: function A(){     this.name = name;} function B(){     //繼承了A,同時傳遞參數     A.call(this,"hello");     // 執行個體屬性;     this.age = 27;}var instance = new B();console.log(instance.name);//helloconsole.log(instance.age);//272.借用建構函式的問題:如果僅僅是借用建構函式那麼也將無法避免建構函式模式存在的問題,方法都在建構函式中定義,因此函數的複用就無從談起。而且在超類型的原型中定義的方法相對,對子類型而言是不可見的,造成的結果是所有的類型都只能使用建構函式模式。三.組合繼承組合繼承,有時也叫為經典繼承,指將原型鏈和借用建構函式的技術組合到一塊,從而發揮二者之長的一種繼承模式,思路是:使用原型鏈實現對原型屬性和方法的繼承,而通過借用建構函式來實現對執行個體屬性的繼承。 function A(name){     this.name = name;     this.colors = ["red","blue"];}A.prototype.sayName = function(){     alert(this.name);};function B(name,age){     A.call(this,name);     this.age = age;}// 繼承方法B.prototype = new A();B.prototype.constructor = B;B.prototype.sayAge = function(){     alert(this.age);};var instance1 = new B("hehe",27);instance1.colors.push("yellow");instance1.sayName();//heheinstance1.sayAge();//27; var instance2 = new B("haha",28);console.log(instance2.colors);//red,blueinstance1.sayName();//hahainstance1.sayAge();//28;

js中的繼承

聯繫我們

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