简体   繁体   中英

Why can't I use Array.join.call in place of Array.prototype.join.call

function test()
{
alert(Array.join.call(arguments,'/')) //alerts /
alert(Array.prototype.join.call(arguments,'/')) //alerts Js/JScript
alert(Array.join(arguments,'/')) //alerts Js/JScript
}
test('Js','JScript');

Why is this difference? Why is it needed to reference prototype first ? Also why does just Array.join gives required result even when join expects just a separator argument.

Array.join is a global function. When using call, what you pass as a first argument is the this object inside the body of the join function, then the arguments for the join function.

js> Array.join.call(null, [1, 2], "/")   
"1/2"

Array.prototype.join is for instances of Array . Therefore, it expects this to be the actual array, which is why your second example works. Your second example amounts to calling Array.prototype.join with the this object being arguments , which is exactly arguments.join("/") . See MDN for an explanation.

This is necessary because the Arguments array isn't actually a real Array Object. . The specification refers to it as 'array-like', but it doesn't contain any of the methods usually associated with JavaScript Arrays, such as join .

Therefore what the above code is doing is calling the Array methods directly, using call , and passing the Arguments object as the scope of the method.

Essentially it causes the interpreter to treat the Arguments array as a real Array so that those methods can be executed on it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM