JavaScript, prototype属性,要慎用

来源:互联网 发布:域名.cn代表什么意思 编辑:程序博客网 时间:2024/05/17 23:48
var R=function() {}R.prototype={p : [],add : function(name){this.p.push(name);},report : function () {alert('array lengh = ' + this.p.length);for (var i=0; i<this.p.length ; i++ ){alert(this.p[i]);}}}var x = new R();x.add("a");var b = new R();b.add("c");x.report();
上面的代码,report() 的结果是,p的长度是2,内容是“a", "c" 而不是期望的1,换句话,这么定义的话,p实际上类似于static了
想和期望的一样,要改下代码
var R=function() {this.p = [];}R.prototype={add : function(name){this.p.push(name);},report : function () {alert('array lengh = ' + this.p.length);for (var i=0; i<this.p.length ; i++ ){alert(this.p[i]);}}}var x = new R();x.add("a");var b = new R();b.add("c");x.report();


原创粉丝点击