JavaScript里的prototype、__proto__和constructor
prototype、__proto__和constructor
来看一段代码:
function Person (name){
this.name = name
}
Person.prototype.getName = function(){
return this.name
}
var alice = new Person('Alice')
alice.getName() //Alice
alice.__proto__ === Person.prototype // true
alice.constructor === Person // true
alice.prototype // undefined
Person.__proto__ === Function.prototype // true
Person.constructor === Funtion // true
Person.prototype.__proto__ === Object.prototype // true
Person.prototype.constructor === Person // true
Person.prototype.prototype // undefined
Object.__proto__ === Function.prototype // true
Object.constructor === Function // true
Object.prototype.__proto__ === null // true
Object.prototype.constructor === Object // true
Function.__proto__ === Function.prototype // true
Function.constructor === Function // true
Function.prototype.__proto__ === Object.prototype // true
Function.prototype.constructor === Function // true
在js中函数都是对象。对象都有__proto__这个隐式原型属性,指向该构造该对象的构造函数的原型。Object.prototype的__proto__指向null,表示不该有值。
所有对象都有constructor属性,表明对象由谁构造。
构造函数除了拥有__proto__属性外,还拥有prototype原型属性,指向构造函数的原型对象。实例对象和原型对象没有prototype属性。