What happens under the hood is that when .slice()
is called normally, this
is an Array, and then it just iterates over that Array, and does its work.(在.slice()
发生的事情是,当正常调用.slice()
时, this
是一个数组,然后它只是遍历该数组,并完成它的工作。)
How is this
in the .slice()
function an Array?(.slice()
函数中的this
怎么样?) Because when you do:(因为当你这样做时:)
object.method();
...the object
automatically becomes the value of this
in the method()
.(...的object
自动成为的值this
在method()
) So with:(所以:)
[1,2,3].slice()
...the [1,2,3]
Array is set as the value of this
in .slice()
.(... [1,2,3]
数组在.slice()
设置为this
的值。)
But what if you could substitute something else as the this
value?(但是,如果你可以用其他东西代替this
值呢?) As long as whatever you substitute has a numeric .length
property, and a bunch of properties that are numeric indices, it should work.(只要你替换的任何东西都有一个数字.length
属性,以及一堆属性为数字索引,它应该有效。) This type of object is often called an array-like object .(这种类型的对象通常称为类似数组的对象 。)
The .call()
and .apply()
methods let you manually set the value of this
in a function.(.apply()
.call()
和.apply()
方法允许您在函数中手动设置this
的值。) So if we set the value of this
in .slice()
to an array-like object , .slice()
will just assume it's working with an Array, and will do its thing.(因此,如果我们的值设置this
在.slice()
到一个数组类的对象 , .slice()
将只是假设它的工作与Array,并会做它的东西。)
Take this plain object as an example.(以此普通对象为例。)
var my_object = {
'0': 'zero',
'1': 'one',
'2': 'two',
'3': 'three',
'4': 'four',
length: 5
};
This is obviously not an Array, but if you can set it as the this
value of .slice()
, then it will just work, because it looks enough like an Array for .slice()
to work properly.(这显然不是一个数组,但是如果你可以将它设置为.slice()
的this
值,那么它就可以正常工作,因为它看起来就像一个数组,可以正常工作.slice()
。)
var sliced = Array.prototype.slice.call( my_object, 3 );
Example: http://jsfiddle.net/wSvkv/(示例: http : //jsfiddle.net/wSvkv/)
As you can see in the console, the result is what we expect:(正如您在控制台中看到的,结果是我们所期望的:)
['three','four'];
So this is what happens when you set an arguments
object as the this
value of .slice()
.(所以当你将一个arguments
对象设置为.slice()
的this
值时会发生这种情况。) Because arguments
has a .length
property and a bunch of numeric indices, .slice()
just goes about its work as if it were working on a real Array.(因为arguments
有一个.length
属性和一堆数字索引, .slice()
就像它在一个真正的数组上工作一样。) 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…