首页 > 代码库 > __proto__和prototype

__proto__和prototype

一个对象的__proto__ 属性和自己的内部属性[[Prototype]]指向一个相同的值 (通常称这个值为原型),原型的值可以是一个对象值也可以是null(比如说Object.prototype.__proto__的值就是null).该属性可能会引发一些错误,因为用户可能会不知道该属性的特殊性,而给它赋值,从而改变了这个对象的原型. 如果需要访问一个对象的原型,应该使用方法Object.getPrototypeOf.


当一个对象被创建时,它的 __proto__ 属性和内部属性[[Prototype]]指向了相同的对象 (也就是它的构造函数的prototype属性).改变__proto__ 属性的值同时也会改变内部属性[[Prototype]]的值,除非该对象是不可扩展的.


什么是内部属性:http://my.oschina.net/xinxingegeya/blog/290167


Be aware that __proto__ is not the same as prototype, since __proto__is a property of the instances (是一个实例的属性)(objects), whereas prototype is a property of the constructor functions used to create those objects.

 

Consider another object called monkey and use it as a prototype when creating objects with the Human() constructor.

var monkey = {
    feeds: ‘bananas‘,
    breathes: ‘air‘
};
function Human() {
}
Human.prototype = monkey;////使用monkey对象重写Human的prototype属性

var developer = new Human();
developer.feeds = ‘pizza‘;
developer.hacks = ‘JavaScript‘;

console.log(developer.hacks);//JavaScript
console.log(developer.feeds);//pizza
console.log(developer.breathes); //air

console.log(developer.__proto__ === monkey); //true

console.log(typeof developer.__proto__); //object
console.log(typeof developer.prototype);//undefined
console.log(typeof developer.constructor.prototype);//object
console.log(typeof developer.constructor); //function


The secret link is exposed in most modern JavaScript environments as the __proto__ property (the word "proto" with two underscores before and two after).

Be aware that __proto__is not the same as prototype, since __proto__is a property of the instances (objects), whereas prototype is a property of the constructor functions used to create those objects.