原型与原型链

123 阅读1分钟

例子

function Text() {

}
var text = new Text();
text.name = '测试';
console.log(text.name, 'text') 

在这个例子中 Text 就是一个构造函数,我们使用 new 创建了一个实例对象 text。

prototype

function Text() {

}
Text.prototype.name = '测试';
var text1 = new Text();
var text2 = new Text();

console.log(text1.name, text1.name, 'text') 

函数的 prototype 属性指向了一个对象,这个对象正是调用该构造函数而创建的实例的原型,也就是这个例子中的 text1 和 text2 的原型。

什么是原型

每一个JavaScript对象(null除外)在创建的时候就会与之关联另一个对象,这个对象就是我们所说的原型,每一个对象都会从原型"继承"属性。

proto

这是每一个JavaScript对象(除了 null )都具有的一个属性,叫__proto__,这个属性会指向该对象的原型。

function Text() {

}
Text.prototype.name = '测试';
var text1 = new Text();
var text2 = new Text();

// console.log(text1.name, text1.name, 'text') 
console.log(text1.__proto__ === Text.prototype); // true

constructor

每个原型都有一个 constructor 属性指向关联的构造函数。

function Text() {

}
Text.prototype.name = '测试';
var text1 = new Text();
var text2 = new Text();

// console.log(text1.name, text1.name, 'text') 
// console.log(text1.__proto__ === Text.prototype);
console.log(Text === Text.prototype.constructor, Text === text1.__proto__.constructor, '测试') // true  true

// ES5
console.log(Object.getPrototypeOf(text1) === Text.prototype) // true

实例与原型

当读取实例的属性时,如果找不到,就会查找与对象关联的原型中的属性,如果还查不到,就去找原型的原型,一直找到最顶层为止。

function Text() {

}
Text.prototype.name = '测试';
var text1 = new Text();
// var text2 = new Text();

// console.log(text1.name, text1.name, 'text') 
// console.log(text1.__proto__ === Text.prototype);
// console.log(Text === Text.prototype.constructor, Text === text1.__proto__.constructor, '测试') // true  true


text1.name = '123';
console.log(text1.name) // 123

delete text1.name;
console.log(text1.name) // 测试

原型的原型

var obj = new Object();
obj.name = '测试'
console.log(obj.name) // 测试

原型对象就是通过 Object 构造函数生成的

原型链

console.log(Object.prototype.__proto__ === null) // true

在原型查找属性的时候查到 Object.prototype 就可以停止查找了。 相互关联的原型组成的链状结构就是原型链