数组复制,深copy
var len = items.length;
var itemsCopy = [];
var i;
// bad
for (i = 0; i < len; i++) {
itemsCopy[i] = items[i];
}
// good
itemsCopy = items.slice();
例子如下:
将一个类数组对象转化为一个数组
function trigger() {
var args = Array.prototype.slice.call(arguments);
...
}
Don't save references to this. Use Function#bind.
// bad
function () {
var self = this;
return function () {
console.log(self);
};
}
// bad
function () {
var that = this;
return function () {
console.log(that);
};
}
// bad
function () {
var _this = this;
return function () {
console.log(_this);
};
}
// good
function () {
return function () {
console.log(this);
}.bind(this);
}
网友评论