您可以扩展Object.prototype
:
Object.prototype.append = Object.prototype.append || function (key,val){
this[key] = val; return this;
};
能够做类似的事情
var value = 'value'
,animal = 'animal'
,ex = {
"amount": 1341,
"data": "tree",
}.append(value,4)
.append(animal,'mouse');
该append
方法可能更全面:
Object.prototype.append = Object.prototype.append || function(){
var args = [].slice.call(arguments);
if (args.length===1 && /object/i.test(args[0].constructor)){
for (var l in args[0]){
if (args[0].hasOwnProperty(l))
this[l] = args[0][l];
}
}
if (args.length===2){ this[args[0]] = args[1]; }
if (args.length>2 && args.length%2<1){
for (var i=0;i<args.length;i+=2){
this[args[i]] = args[i+1];
}
}
return this;
};
现在你可以:
var value = 'value'
,animal = 'animal'
,amount = 'amount'
,data = 'data'
,ex = {}.append(amount,1341,data,'tree',value,4,animal,'mouse');
另请参阅此页面(关于扩展本机 JS 对象)