您现在的位置是:首页 > 电脑技术查询 > web开发

第2段代码为什么会出错?该怎么处理

编辑:chaxungu时间:2022-10-02 23:15:40分类:web开发

第2段代码为什么会出错?
JScript code function Odemo(){} var a=new Odemo(); Odemo.prototype.sayName=function(name) { return this.name=name; } alert(a.sayName('asd')); //显示asd

JScript code function Odemo(){} var a=new Odemo(); Odemo.prototype={ name:'asd', sayName:function(){ return this.name; } } alert(a.sayName()); //为什么会报错

JScript code function Odemo(){} Odemo.prototype={ name:'asd', sayName:function(){ return this.name; } } var a=new Odemo(); alert(a.sayName()); //显示asd只不过是代码所编写的位置不同而已,
为什么第2段代码会出错呢?

第一段代码不也是在var a=new Odemo();的下面编写的么?


------解决方案--------------------
Odemo.prototype={
name:'asd',
sayName:function(){
return this.name;
}
}
这种方式会切断以前生成的对象之间的联系,只与后面创建的对象有影响,因为
{
name:'asd',
sayName:function(){
return this.name;
}
}是一个新的对象,Odemo.prototype的引用已经改变,而之前创建的对象中保持的还是之前的Odemo.prototype的引用