天天看點

構造函數與原型對象和執行個體對象的關系

構造函數與原型對象和執行個體對象的關系

//通過構造函數執行個體對象,并初始化
//var arr=new Array(10,20,30,40);
//join是方法,執行個體對象調用的方法
//arr.join("|");
//console.dir(arr);
//join方法在執行個體對象__proto__原型
//console.log(arr.__proto__==Array.prototype);
           
//原型的作用之一:共享資料,節省記憶體空間
//構造函數
function Person(age,sex) {
  this.age=age;
  this.sex=sex;
}
//通過構造函數的原型添加一個方法
Person.prototype.eat=function () {
  console.log("明天中午吃完飯就要演講,好痛苦");
};
var per=new Person(20,"男");
// per.__proto__.eat();
per.eat();
// per.eat();
           
//構造函數,原型對象,執行個體對象之間的關系

console.dir(Person);
//console.dir(per);
           

結論 構造函數中的prototype 即Person.prototype == 執行個體對象中的__proto__ 即per.__proto__

兩者共用一塊記憶體空間即 per.__proto__指向Person.protoype

構造函數與原型對象和執行個體對象的關系

而構造函數中的prototype的constructor構造器指向的自身

構造函數與原型對象和執行個體對象的關系

繼續閱讀