標籤:可見 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中的繼承