一文掌握JS的原型与继承

215 阅读1分钟

proto 与 prototype

function Person() {};
var a = new Person();


// 实例的原型对象 和 其构造函数的原型对象(Person.prototype) 所指向的是同一个对象
console.log(a.__proto__ === Person.prototype)  // true

// 只有对象才有 __proto__ 属性,

// 那么Object 构造函数本身也是对象,所有构造函数就有 __proto__ 和 prototype 两个属性
// 所以 Object.__proto__ 指向其构造函数的原型对象指向的对象
console.log(Person.__proto__ === Function.prototype);  // true

// 那么 Function 本身也是构造函数,所以他也有 __proto__ 和 prototype

console.log(Function.__proto__ === Function.prototype); // true
// 你没看错,就是指向自己的 原型对象

那 constructor 又是啥?

constructor 是存在构造函数的原型对象上,指向该构造函数


console.log(Person.prototype.constructor === Person); // true

// 等价于
console.log(a.__proto__.constructor === Person); // true

继承 extends

// function A 要继承 function B
function myExtends(A, B) {
    var F = function() {};
    F.prototype = B.prototype;
    A.prototype = new F();
}

function A () {};


function B () {};
B.prototype = {
    b: 'b'
}

myExtends(A, B);
A.prototype.a = 'a'


var a = new A();

console.log(a.a);
console.log(a.b);

a.a 查找很容易,在a.prototype上就能找到。

a.b 的查找路径是怎么样的

// a.__proto__ === A.prototype === F的实例
// F的实例.__proto__ === F.prototype === B.prototype
// 最终找到B.prototype  找到b属性