简体   繁体   中英

Array() and Array.prototype usage

First of all i would like to ask for excuse if answer is obvious, and/or easy to find. I didn't find any complete answers.

The question is very simple:

var array1 = Array().slice.call(arguments,1);
var array2 = Array.prototype.slice.call(arguments,1);

They do the same thing. Can you do in such a way for Object, Date, String, etc prototypes

Yes you can, simply because each instance inherits from its constructor's prototype.

That is (new Array()).slice (or better, [].slice ) is exactly the same method as Array.prototype.slice .

The second approach is better, as you're not creating an Array that is otherwise unused. With the first approach, you're constructing an array, and then using dynamic prototype chain resolution to locate it's slice method, which you then call using your arguments as the context. The second approach directly access the slice method, so you're avoiding the object creation and prototype chain resolution, so it's all around better.

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