1. 程式人生 > >一張圖讓你徹底理解js原型鏈

一張圖讓你徹底理解js原型鏈

function Person() {
    this.name = 'sanlyshi';
    this.age = '23';
    this.eat = function () {
        console.log(this.name +' is eating!')
    }
}
Person.prototype.smell = function () {
    console.log("smell");
};
var person1 = new Person();
console.log(person1.name);   //sanlyshi
person1.eat();               
//sanlyshi is eating! person1.smell(); //smell // 每個"函式"都有一個prototype屬性,指向一個"物件" // "物件"具有屬性__proto__,可稱為隱式原型,一個物件的隱式原型指向構造該物件的建構函式的原型 // 1 console.log(Object.prototype.__proto__ === null); //true // 2 console.log(Function.prototype.__proto__ === Object.prototype); //true // 3 console.log(Person.__proto__ === Function.prototype);
//true // 4 console.log(person1.__proto__ === Person.prototype); //true // "prototype物件"有一個constructor屬性,預設指向prototype物件所在的建構函式 console.log(Person.prototype.constructor === Person); //true console.log(Function.prototype.constructor === Function); //true console.log(Object.prototype.constructor === Object);
//true