Javascript 为什么下划线别名方法会脱离原型链?
然后使用Javascript 为什么下划线别名方法会脱离原型链?,javascript,underscore.js,Javascript,Underscore.js,然后使用call()调用它们 例如,可以直接这样调用slice obj.slice(1); 但下划线确实如此 slice.call(obj, 1); 原因是什么?以防对象切片与您想象的不同 特别是,类似数组的对象,如参数或节点列表,没有切片方法。我对下划线没有太多经验,但我认为这是因为下划线使用类似数组的对象而不是数组 在这种情况下,它没有数组的方法,因此必须使用call方法 见以下示例: function List(){ this.length = arguments.length
call()
调用它们
例如,可以直接这样调用slice
obj.slice(1);
但下划线确实如此
slice.call(obj, 1);
原因是什么?以防对象切片与您想象的不同
特别是,类似数组的对象,如
参数
或节点列表,没有切片
方法。我对下划线没有太多经验,但我认为这是因为下划线使用类似数组的对象而不是数组
在这种情况下,它没有数组的方法,因此必须使用call方法
见以下示例:
function List(){
this.length = arguments.length;
//arguments is an array like object, not an array, does not have a foreach method
Array.prototype.forEach.call(arguments, function(val, index){
this[index] = val;
}, this);
}
var list = new List(1,2,3,4,5);
console.log(list); //{ '0': 1, '1': 2, '2': 3, '3': 4, '4': 5, length: 5 }
//Cannot use push on on object List
//list.push(6); //TypeError: undefined is not a function
//But you can use call()
Array.prototype.push.call(list, 6);
console.log(list);
//{ '0': 1, '1': 2, '2': 3, '3': 4, '4': 5, '5': 6, length: 6 }
链接到上面的例子
编辑:我错过了一些重要的事情
通过设置var slice=Array.prototype.slice
使用slice.call()
,这样slice方法就可以引用此变量
请查看以下示例:
var push = Array.prototype.push;
push.call(list, 7);
console.log(list);
//{ '0': 1, '1': 2, '2': 3, '3': 4, '4': 5, '5': 6, '6': 7, length: 7 }
List.prototype.push = push;
list.push(8);
console.log(list);
//{ '0': 1, '1': 2, '2': 3, '3': 4, '4': 5, '5': 6, '6': 7, '7': 8, length: 8 }