在学习JavaScript的prototype的时候有个问题不太明白,prototype属性,可以返回对象类型原型的引用,如果对象创建在修改原型之前,那么该对象不会拥有修改后的原型方法,请帮忙解释下什么原理?
[code="js"]
function Rectangle(width,height){ this.width =width; this.height = height; } Rectangle.prototype.area = function(){return this.width*this.height} function ColorRectangle(color,width,height){ Rectangle.call(this,width,height); this.c = color; } var cret = new ColorRectangle('red',10,10); ColorRectangle.prototype = new Rectangle(5,5); alert(cret.area()); //error, "cret.area is not a function"[/code]
参考ECMAScript
Function Definition -> Creating Function Objects -> [[Construct]]
里面有说明Function用于new构造对象时的处理过程,对象的[[prototype]]在构造时已经设定完毕,而不是每次访问都去查找构造函数,再查询构造函数的prototype属性。
就是说原型链的改变,不会影响之前产生的对象
<!-- function obj(){ } var o1=new obj(); obj.prototype={a:"aaa"}; var o2=new obj(); alert(o1.a); alert(o2.a); //-->