In response to a previous question, I received this helpful answer:
for (var i in someArray) {
if ({}.hasOwnProperty.call(someArray, i))
alert(someArray[i]);
}
My questions are:
Where can I read about the {} construct? I cannot find it in the jQuery docs, and it is impossible to google for.
Where can I read about the call() function. Searching the jQuery API site does not turn up anything seemingly related.
Thanks.
{} is one way to declare an empty object. It is called object literal syntax and you can read more about it here.
The call() method is a JavaScript method (not jQuery). Again, you can read more about it here. Basically, call() allows you to change the value of this inside the function you're calling call() on. It is related to apply();
var array = new Array;
function foo() {
alert(this === array);
};
foo(); // false;
foo.call(array); // true
Looking at the code in particular, we're looping over an array and using the hasOwnProperty method to check the value (i) exists on the someArray array (as opposed to being in the prototype chain of someArray.
As for why we're using {}.hasOwnProperty as opposed to someArray.hasOwnProperty, I guess that the user might be protecting against hasOwnProperty being declared on someArray (by using an empty object). If he hadn't done this, then the following could have been possible;
var someArray = [];
someArray.hasOwnProperty = function () {
return true; // always return true... muahahaha.
}
Or even;
var someArray = [];
someArray.hasOwnProperty = 4; // now hasOwnProperty isn't even a function. Calling someArray.hasOwnProperty() will result in an error.
http://www.dyn-web.com/tutorials/obj_lit.php
http://www.webreference.com/js/column26/call.html
So Google on 'javascript object literal', or 'javascript call method'.. couple of examples linked above.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With