javascript prototype和__proto__和繼承的機制

//爲什麼prototype的出現?prototype 爲了暴露公共的屬性(從而實現繼承) 私有的屬性就在構造函數裏面實現(變量的局部性)
function DOG(name){

    this.name = name;

  }

  DOG.prototype = { species : '犬科' };


  var dogA = new DOG('大毛');

  var dogB = new DOG('二毛');


  alert(dogA.species); // 犬科

  alert(dogB.species); // 犬科


DOG.prototype.species = '貓科';


  alert(dogA.species); // 貓科

  alert(dogB.species); // 貓科
//這樣就實現了  實例dogA和實例dogB的私有屬性name互不受影響 dogA和dogB共享公共屬性species

  //普通對象
  let _simple={param:1};
  console.log(_simple.__proto__===Function.prototype);
  console.log(_simple.__proto__===Object.prototype);

function Foo(){};//函數對象 構造函數
var f1 = new Foo();//f1爲實例對象
console.log(f1.prototype);
//undefined 實例對象沒有prototype 爲什麼有__proto__?  
//那怎麼把實例對象與函數對象關聯起來 引入__proto__這個屬性 指向函數對象的prototype 這樣實例對象就具有函數對象portotype的方法了
console.log(f1.constructor===Foo.prototype.constructor);
//true 實例對象調用prototype上的方法====函數對象原型上的方法 由於__proto__指向Foo.prototype 實例對象自然就可以調用prototype的方法
console.log(typeof Foo);
console.log(f1.__proto__===Foo.prototype);//true
console.log(Foo.__proto__===Function.prototype);//true
console.log(Function.__proto__===Object.prototype);//true

console.log(Foo===Foo.prototype.constructor);
//Foo這個構造函數 實際上就是Foo原型上的constructor方法 Foo.prototype.constructor 就相當於Foo.prototype.constructor 直接指向Foo這個方法
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章