Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the JavaScript constructs `{}` and `call()`?

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.

like image 473
dotancohen Avatar asked Sep 05 '26 04:09

dotancohen


2 Answers

  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.
like image 178
Matt Avatar answered Sep 07 '26 18:09

Matt


  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.

like image 38
James Gaunt Avatar answered Sep 07 '26 18:09

James Gaunt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!