0

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

0

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

6 Comments

It should be noted that while this works for Arrays because of the way the spec sets up behavior of Array (as a constructor) when called as a function, this does not necessarily extend to the other objects mentioned in the question. For example, if you do Date.prototype.test = 1; and then Date().test, you get nothing because of the way Date (as a constructor) acts as a function.
Yes, I was thinking about mentioning this, but I did not want to make it too confusing. It's enough to say that Date does not return a Date instance when called without the new keyword (it returns a string).
Yeah, I think the constructor/function duality is probably more of the one confusing aspects of JavaScript.
For example? Number().toFixed.call(5.12, 1) is the same as Number.prototype.toFixed.call(5.12, 1)...
@Elmor: Ah well, that is something completely different. You cannot assign properties to primitive values.
|
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.