fe-interview icon indicating copy to clipboard operation
fe-interview copied to clipboard

来说说你对原型链的理解?

Open habc0807 opened this issue 4 years ago • 1 comments

原型链几乎是前端面试的必问题目

habc0807 avatar Aug 14 '20 02:08 habc0807

1.是什么
每一个实例对象都有一个私有属性__proto__指向其构造函数的原型对象prototype,该原型对象也会作为实例对象有一个私有属性__proto__,层层向上直到一个对象的原型对象值为null。
当访问一个对象的属性或方法时,js引擎会先查找该对象本身是否包含,如果没有,会去该对象的__proto__属性所指向的原型对象上找,如果没有,会继续向上一层找,直到某个对象的__proto__值为null,这就是原型链。
function func(){};
console.log(func.prototype);    
var foo=new func();
console.log(foo.__proto__);
两个输出结果一样,大致如下:
{
    constructor: ƒ func(),
    __proto__: {
        constructor: ƒ Object(),
        hasOwnProperty: ƒ hasOwnProperty(),
        isPrototypeOf: ƒ isPrototypeOf(),
        propertyIsEnumerable: ƒ propertyIsEnumerable(),
        toLocaleString: ƒ toLocaleString(),
        toString: ƒ toString(),
        valueOf: ƒ valueOf()
    }
}
console.log(foo.__proto__===func.prototype);     //true

console.log(func.prototype.__proto__);
console.log(Object.prototype);
返回结果相同,大致:
{
        constructor: ƒ Object(),
        hasOwnProperty: ƒ hasOwnProperty(),
        isPrototypeOf: ƒ isPrototypeOf(),
        propertyIsEnumerable: ƒ propertyIsEnumerable(),
        toLocaleString: ƒ toLocaleString(),
        toString: ƒ toString(),
        valueOf: ƒ valueOf()
}
返回结果中没有__proto__属性
console.log(func.prototype.__proto__===Object.prototype);    //true
console.log(Object.prototype.__proto__);      //null
由此:
foo.__proto__===func.prototype
foo.__proto__.__proto__===func.prototype.__proto__===Object.prototype
Object.prototype.__proto__  值为null

原型链为
foo => foo.__proto__===func.prototype => foo.__proto__=== Object.prototype =>null

同时构造函数的prototype   的constructor属性   对应   该实例对象的构造函数:
console.log(func.prototype.constructor);              //func()
console.log(Object.prototype.constructor);          //Object()
2.作用
原型链为了实现继承

    引自:
https://stackoverflow.com/questions/9959727/proto-vs-prototype-in-javascript
https://medium.com/@chamikakasun/javascript-prototype-and-prototype-chain-explained-fdc2ec17dd04

    
    

AMY-Y avatar Aug 16 '20 10:08 AMY-Y