问题描述
function fn(o){ arguments.callee.prorotype={ shout:function(){ alert('shout'); } } for(var i in o) this[i]=o[i]}var obj = new fn({name:'eric'});obj.shout();//error下面这样写就不报错:function fn(o){ for(var i in o) this[i]=o[i]}fn.prorotype={ shout:function(){ alert('shout'); }}var obj = new fn({name:'eric'});obj.shout();//shout
解决方案
你可以看看ECMAScript文档中的 Function -> Construct 这节(4版 13.2.2)对JS函数(假定为F)对象使用new操作符,进行构造(Construct)时,它的处理步骤如下:(翻译后的简化版,部分不常用分支移掉了)创建一个新的空对象o将o的原型([[prototype]])设定为F的prototype属性以o为this指针调用构造函数在你这里,创建obj的时候,在执行到fn内部的代码之前,它的[[prototype]]即原型链已设定完毕,在fn内部的修改不影响到obj了。你可以试试用这个:arguments.callee.prorotype.should = function(){}它修改了原型对象的属性,可以影响到obj附原版:When the [[Construct]] property for a Function object F is called, the following steps are taken:1. Create a new native ECMAScript object.2. Set the [[Class]] property of Result(1) to "Object".3. Get the value of the prototype property of the F.4. If Result(3) is an object, set the [[Prototype]] property of Result(1) to Result(3).5. If Result(3) is not an object, set the [[Prototype]] property of Result(1) to the original Objectprototype object as described in 15.2.3.1.6. Invoke the [[Call]] property of F, providing Result(1) as the this value and providing the argumentlist passed into [[Construct]] as the argument values.7. If Type(Result(6)) is Object then return Result(6).8. Return Result(1).