每个JS对象连接到一个原型对象,并从中继承属性。原型连接只有在检索值的时候才会被用到,如果我们尝试去获取对象的某个属性,而该对象并没有此属性名,那么JS会尝试从原型对象中获取。如果该原型对象也不存在该属性,那么将再到该原型对象的原型对象中去检索,以此类推,直到Object.prototype。
function
Test() {
// fn
}
Test.prototype = {
foo: ' bar '
};
var instance = new Test();
instance.foo === ' bar ' ; // 从原型对象中获取foo的值
// fn
}
Test.prototype = {
foo: ' bar '
};
var instance = new Test();
instance.foo === ' bar ' ; // 从原型对象中获取foo的值
如果我们更新该对象的foo属性,原型对象的foo将保持不变:
instance.foo
=
'
change
'
;
instance.foo == = ' change ' ; // 该对象存在foo属性,所以不再到原型对象中检索
delete instance.foo; // 删除该对象的foo属性
instance.foo == = ' bar ' ;
instance.foo == = ' change ' ; // 该对象存在foo属性,所以不再到原型对象中检索
delete instance.foo; // 删除该对象的foo属性
instance.foo == = ' bar ' ;