Reputation: 13916
In JavaScript, I wonder why I can do this:
[].slice.apply([1,2,3], [0, 2]) // returns [1, 2]
Which is as far as I understand equivalent of this:
Array.prototype.slice.apply([1,2,3], [0, 2]); // returns [1, 2]
But I can't do this:
{}.hasOwnProperty.apply(a, ['a']);
Which would allow to not type this long line:
Object.prototype.hasOwnProperty.apply(a, ['a']); // returns true or false
Well, while I am at it, I also see that I can actually do all of these:
''.indexOf.apply('asdasd', ['s']); // returns 1
true.toString.apply(true); // returns // "true" as string
What the deal with {} ? :-) Why is it special?
Upvotes: 0
Views: 256
Reputation: 360026
Is hasOwnProperty('a')
a typo?
{}.hasOwnProperty.apply(a, ['a']);
But that doesn't quite work due to JavaScript interpreting {}
as block delimiters. Just add parentheses:
({}).hasOwnProperty.apply(a, ['a']);
Check it:
> var a = {'a': 1}
Object
> {}.hasOwnProperty.apply(a, ['a']);
SyntaxError: Unexpected token .
> ({}).hasOwnProperty.apply(a, ['a']);
true
Upvotes: 6
Reputation: 45565
Brackets:
({}).hasOwnProperty.apply({k:9,aa:5}, ['a']); // false
({}).hasOwnProperty.apply({k:9,a:5}, ['a']); // true
Upvotes: 2
Reputation: 32552
hasOwnProperty() returns true or false, not the actual property itself.
With your other examples, you are working with functions that are returned, not scalars or native objects, which is why you can call apply() on them.
Have you tried {}.hasOwnProperty.apply(......)?
Upvotes: 2