fire8119 2010-09-11 22:39
浏览 277
已采纳

为什么在构造函数内部定义原型报错

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

  • 写回答

1条回答 默认 最新

  • cyrilluce 2010-09-13 09:45
    关注

    你可以看看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 Object
    prototype 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 argument
    list passed into [[Construct]] as the argument values.
    7. If Type(Result(6)) is Object then return Result(6).
    8. Return Result(1).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 虚拟机打包apk出现错误
  • ¥30 最小化遗憾贪心算法上界
  • ¥15 用visual studi code完成html页面
  • ¥15 聚类分析或者python进行数据分析
  • ¥15 逻辑谓词和消解原理的运用
  • ¥15 三菱伺服电机按启动按钮有使能但不动作
  • ¥15 js,页面2返回页面1时定位进入的设备
  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝