[求助]JavaScript构造函数原型对象中属性的修改问题
这是我在使用原型化构造函数时意外遇到的问题。下面是代码:
<script type="text/javascript">function Cons(){ //声明构造函数 Cons() Cons.prototype.info="something"; Cons.prototype.showInfo=function(){ alert(this.info); }}Cons.prototype.info="changed!"; //尝试修改原型中的属性var inst=new Cons(); //建立实例 instinst.showInfo(); //修改无效,警告"something"</script>
//...var inst=new Cons(); //建立实例 instCons.prototype.info="changed!"; //尝试修改原型中的属性inst.showInfo(); //警告"changed!"//...
<script type="text/javascript">function Cons(){ //声明构造函数 Cons() Cons.prototype.info="something"; Cons.prototype.showInfo=function(){ alert(this.info); }}Cons.prototype.newInfo="new!"; //尝试在原型中添加属性var inst=new Cons(); //建立实例 instalert(inst.newInfo); //有效,警告"new!"</script>