1. 程式人生 > >繼承再理解

繼承再理解

sister 一次 false undefine defined javascrip peer 影響 prop

function Super(){
    this.name = ‘man‘;
    this.arr = [1,2,3]
}
var a = new Super();
a.name = ‘woman‘;
a.arr.push(4);
console.log(a.name);   // woman
console.log(a.arr);  // [1,2,3,4]
var b = new Super();
console.log(b.name);  // man
console.log(b.arr);  // [1,2,3]

 在沒有繼承的情況下,new出來的實例深度復制了構造函數中的屬性

function
SuperClass(){ this.name = "women"; this.bra = ["a","b"]; } function SubClass(){ this.subname = "your sister"; } SubClass.prototype = new SuperClass(); var sub1 = new SubClass(); sub1.name = "man"; sub1.bra.push("c"); console.log(sub1.name);//man console.log(sub1.hasOwnProperty(‘name‘)) //true console.log(sub1.bra);//
["a","b","c"] var sub2 = new SubClass(); console.log(sub2.hasOwnProperty(‘name‘)) //false console.log(sub2.name);//woman console.log(sub2.bra);//["a","b","c"]

證明了僅通過原型鏈繼承的話,子類的實例共享子類的原型對象(也就是共享父類的實例,父類實例化了一次,也就是僅僅深拷貝了一次)

function SuperClass() {
  this.name = "women";
  this.bra = ["a", "b"];
}
function
SubClass() { this.subname = "your sister"; //將SuperClass的作用域賦予當前構造函數,實現繼承 SuperClass.call(this); } var sub1 = new SubClass(); sub1.bra.push("c"); console.log(sub1.bra);//["a","b","c"] var sub2 = new SubClass(); console.log(sub2.bra);//["a","b"]
function SuperClass() {
  this.name = "women";
  this.bra = ["a", "b"];
}
SuperClass.prototype.sayWhat = function(){
  console.log("hello");
}
function SubClass() {
  this.subname = "your sister";
  SuperClass.call(this);
}  
var sub1 = new SubClass();
console.log(sub1.sayWhat());//TypeError: undefined is not a function

而通過借用構造函數的方法來繼承的話,每個子類的實例中都有了父類構造函數的屬性(深拷貝),但要是方法在構造函數中的化,那就造成浪費內存,沒有實現方法的服用,

而且僅通過這種方式實現繼承的化,父類的原型中的方法繼承不到;

function SuperClass() {
  this.name = "women";
  this.bra = ["a", "b"];
}
SuperClass.prototype.sayWhat = function(){
  console.log("hello");
}
function SubClass() {
  this.subname = "your sister";
  SuperClass.call(this);       //第二次調用SuperClass
}
SubClass.prototype = new SuperClass(); //第一次調用SuperClass
var sub1 = new SubClass();
console.log(sub1.sayWhat());//hello

因此可以通過原型鏈 + 借用構造函數實現:每個子類的實例中都有了父類構造函數的屬性(深拷貝,然後每個子類實例跟父構造函數擁有相同的屬性,因此僅查找它自身,而不會 沿著原型鏈去查找,從而實現了改變自身不影響別人),而要復用的,一般是方法,就放在原型對象上。

繼承再理解