原型与原型链

97 阅读1分钟

原型

var People = function() {}

var Other = function() {}

var people = new People()

var other = new Other()

people.__proto__ = People.prototype

People = People.prototype.constructor

People.prototype.__proto__ = Object.prototype

Object.prototype.constructor = Object

Object.prototype.__proto__ = null

当读取实例属性时,如果找不到,就会查找对象关联的原型,如果查不到就会查原型的原型,直到最顶为止,Object没有值。

原型链

每个构造函数都有一个原型对象(People.prototype),原型对象都包含一个指向构造函数的指针(People.prototype.constructor = People)

而实例都包含一个指向原型对象的内部指针(people.__proto__),如果让原型对象等于另一个类型的实例,原型对象将包含一个指向另一个原型的指针

( 

    People.prototype = new Other();

    People.prototype.__proto__ = Other.prototype;

    People.prototype.__proto__.constructor = Other;

    People.prototype.__proto__.__proto__ = Other.prototype.__proto__ = Object.prototype;

)

假如另一原型对象中也包含着指向另一个类型的实例,关系层层递进,构成实例与原型的链条,这就是原型链的基本概念。