3

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:

  1. Where can I read about the {} construct? I cannot find it in the jQuery docs, and it is impossible to google for.

  2. Where can I read about the call() function. Searching the jQuery API site does not turn up anything seemingly related.

Thanks.

Community
  • 1
  • 1
dotancohen
  • 30,064
  • 36
  • 138
  • 197

3 Answers3

5
  1. {} is one way to declare an empty object. It is called object literal syntax and you can read more about it here.

  2. 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.
Matt
  • 74,352
  • 26
  • 153
  • 180
  • The hasOwnProperty check is there to protect against undefined objects in the array, as not all the array elements are sequential. Thanks! – dotancohen Feb 17 '12 at 11:38
4
  1. {} is an object literal (pure javascript) nothing to do with jQuery

http://www.dyn-web.com/tutorials/obj_lit.php

  1. call method is again pure javascript, not jQuery specific

http://www.webreference.com/js/column26/call.html

So Google on 'javascript object literal', or 'javascript call method'.. couple of examples linked above.

James Gaunt
  • 14,631
  • 2
  • 39
  • 57
3

You are confusing jQuery and JavaScript.

{} is a JavaScript construct and is an empty object.

call() method is also part of JavaScript

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
Jan Hančič
  • 53,269
  • 16
  • 95
  • 99