function s(){};
s.prototype={
_cols:[],
drawTitle:function(titles){
var me=this;
titles=titles||[];
var c={name:'',width:10,type:'multi'};
titles.splice(0,0,c);//向titles数组在0位置上插入一个对象
for(var j=0;j<titles.length;j++){
this._cols[j]=titles[j];
}
}
}var a=new s();
alert(s.prototype._cols.length)//原型的属性不会因实例中的属性变化而变化吧?
a.drawTitle([1,2,3]);
alert(s.prototype._cols.length)//但它确实变了!以上代码怎么把原型中的_cols属性变掉了呢?感觉是splice函数可能对数组的引用产生的问题,但是不明白为什么?
function s()
{
}
s.prototype = {
_cols: [],
init:function(_cols)
{
this._cols=_cols;
},
drawTitle: function(titles)
{
var me = this;
titles = titles || [];
var c = { name: '', width: 10, type: 'multi' };
titles.splice(0, 0, c); //向titles数组在0位置上插入一个对象
for (var j = 0; j < titles.length; j++)
{
this._cols[j] = titles[j];
}
}
} var a = new s();
a.init([]);
alert(s.prototype._cols.length)//原型的属性不会因实例中的属性变化而变化吧?
a.drawTitle([1, 2, 3]);
alert(s.prototype._cols.length)//这个不变
alert(a._cols.length); //这个变
我觉得是splice的问题,但是splice有什么特殊的呢?每个实例的属性应该互不影响才是。
to:
titles.unshift(c);//向titles数组在0位置上插入一个对象
function s(){};
s.prototype={
_cols:[],
drawTitle:function(titles){
for(var j=0;j<titles.length;j++){
this._cols[j]=titles[j];
}
}
}var a=new s();
alert(s.prototype._cols.length)
a.drawTitle([1,2,3]);
alert(s.prototype._cols.length)
是数组对象的特殊吗?怎么会影响到原型的属性呢
s.prototype={
_cols:[],
drawTitle:function(titles){
var me=this;
titles=titles||[];
var c={name:'',width:10,type:'multi'};
titles.splice(0,0,c);//向titles数组在0位置上插入一个对象
for(var j=0;j<titles.length;j++){ //循环赋值
this._cols[j]=titles[j];
}
}
}var a=new s();
a.drawTitle([1,2,3]);
alert(a._cols);
alert(s.prototype._cols)
delete a._cols; //揭示关键之所在
alert(a._cols);
alert(s.prototype._cols);
直接赋值方式:function s(){};
s.prototype={
_cols:[],
drawTitle:function(titles){
var me=this;
titles=titles||[];
var c={name:'',width:10,type:'multi'};
titles.splice(0,0,c);//向titles数组在0位置上插入一个对象
this._cols=titles; //直接赋值
}
}var a=new s();
a.drawTitle([1,2,3]);
alert(a._cols);
alert(s.prototype._cols)
delete a._cols; //揭示关键之所在
alert(a._cols);
alert(s.prototype._cols);
大家分别运行一下上面的两段代码就明白了