網(wǎng)站建設(shè)修改建議書店鋪如何運營和推廣
借用原型對象繼承父類型方法
目的: 兒子繼承父類屬性和方法,父類之后新增的方法不會被兒子繼承。
前言:
先理解一個問題:
Son.prototype = Father.prototype;
這一操作相當(dāng)于把Son的原型對象指向Father。
意味著Son的prototype的地址與Father一致,如果我給Son新增函數(shù),那么Father也會同步新增。
具體代碼:
function Father(uname, age) {this.uname = uname;this.age = age;
}
Father.prototype.money = function() {console.log(100000);};
function Son(uname, age, score) {Father.call(this, uname, age);this.score = score;
}
Son.prototype = Father.prototype;let son = new Son('劉德華', 18, 100);
console.log(Son.prototype);
console.log(Father.prototype);
結(jié)果:
分析:
我們的初衷是,兒子繼承父類屬性和方法,父類之后新增的方法不會被兒子繼承。
很明顯兒子和父親的成員函數(shù)和屬性都一致,這是由于兒子和父類地址一致導(dǎo)致的。
解決方案:
Son.prototype = new Father();
首先用new創(chuàng)建一個父類的實例對象,然后讓Son的原型對象指向這個新創(chuàng)建的對象即可。
從下往上理解:
Son原型對象:指向Father實例對象,繼承Father實例對象的屬性和方法
Father實例對象:含有__proto__屬性,可以使用Father原型對象的新增的方法
Father原型對象:可以新增函數(shù)
此時,如果Son新增函數(shù),由于Son和Father實例對象地址一致,只會影響到Father實例對象,而不會影響到Father原型對象上。
總結(jié):
將子類所共享的方法提取出來,讓子類的 prototype 原型對象 = new 父類()
通過父類實例化對象,開辟額外空間,就不會影響原來父類的原型對象。
有一說一,采用了深拷貝的思想。
-
Code:
// 借用父構(gòu)造函數(shù)繼承屬性 // 1. 父構(gòu)造函數(shù) function Father(uname, age) {// this 指向父構(gòu)造函數(shù)的對象實例this.uname = uname;this.age = age; } Father.prototype.money = function() {console.log(100000);}; // 2 .子構(gòu)造函數(shù) function Son(uname, age, score) {// this 指向子構(gòu)造函數(shù)的對象實例Father.call(this, uname, age);this.score = score; } // Son.prototype = Father.prototype; 這樣直接賦值會有問題,如果修改了子原型對象,父原型對象也會跟著一起變化 Son.prototype = new Father(); // 如果利用對象的形式修改了原型對象,別忘了利用constructor 指回原來的構(gòu)造函數(shù) Son.prototype.constructor = Son; // 這個是子構(gòu)造函數(shù)專門的方法 Son.prototype.exam = function() {console.log('孩子要考試');} var son = new Son('劉德華', 18, 100); console.log(son); console.log(Father.prototype); console.log(Son.prototype.constructor);
參考:
可以看這兩集
https://www.bilibili.com/video/BV1DY41177dM?p=37&spm_id_from=pageDriver&vd_source=30a98e03cd5a7bbfaeb4416fc48542e2