prototype、__proto__、constructor

154 阅读2分钟

constructor

constructor始终指向它的构造函数

var x = 1
x.constructor // ƒ Number() { [native code] }
// x是数字,是Number函数的实例

下个结论,实例都有一个constructor属性指向这个实例的构造函数,那么是否据有constructor属性的都是实例呢?
比如构造函数的原型对象(根据红宝书第三版:每个构造函数都有一个原型对象,原型对象都包含一个指向构造函数的内部指针)
可以用instanceof进行检测

function A (){
    this.a = 1
}
A.prototype.constructor === A // true
A.prototype // {constructor: ƒ}
A instanceof Function // true
A.prototype instanceof Object // true

那么可以下个结论一般情况下,实例都会有一个constructor属性去指向它的构造函数

__proto __(隐形原型)

根据红宝书第三版:实例都包含一个指向构造函数的原型对象的内部指针。
(只有在游览器里面才能访问)

function Father(){
    this.role = 'father'
}
Father.__proto__ === Function.prototype // true
Father.prototype instanceof Object // true
Father.prototype.__proto__ === Object.prototype // true
let child = new Father()
child.__proto__ === Father.prototype // true

prototype (原型)

对于prototype的使用,其实在一般的开发中,很难遇见,大多时候都是直接使用别人的轮子。 如果真的要理解的话,这可以说是“基因”,而基因都是肉眼看不见的。

function Father(){}
Father.prototype.color = 'yellow' // color就是基因项,而prototype就是基因
let child = new Father()
child.color // yellow

child 完全继承了Father的“基因”,那么child的“基因”是什么

child.prototype // undefined

为什么勒,按道理应该和Father的prototype一样才对啊。

红宝书第三版:我们创建的每一个函数都有一个prototype(原型属性),这个属性是一个指针,指向一个对象(原型对象)。

那问题来勒,是否只有函数才具备prototype属性

function Father(){}
Father.prototype.color = 'yellow' // color就是基因项,而prototype就是基因
let child = new Father()
child.color // yellow
child.prototype // undefined
child.prototype = {a:1}
child.a // undefined

说明child没有prototype属性,而我们写的只是在child上定义了一个prototype属性假的原型。那么child里面到底有没有prototype,是有的。
child是Father的实例。 那么child的内部有指向构造函数的指针,可以通过这个指针去访问构造函数的原型对象,而且child还有一个指向构造函数的原型对象的内部指针。

child.constructor // Father
child.constructor.prototype // 结果是Father.prototype
child.__proto__ // 结果是Father.prototype
child.__proto__ === child.constructor.prototype // true

结论:创建的函数有prototype(显示原型),其他的有__proto__(隐式原型),prototype是指向原型对象的,这个原型对象其实是Object的实例。而__proto__是指向构造函数的原型对象的。这不是说__proto__指向的是prototype,因为prototype也是指针,他们两个都指向原型对象。区别在于,__proto__是在实例上,prototype是在函数上。 那么函数有没有__proto__属性勒。有的,函数的__proto__指向Function.prototype

function Father(){}
Father instanceof Function // true, Father 是Function的实例
Father.__proto__ === Function.prototype // true