Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bracket notation with Object.hasOwnProperty?

Tags:

javascript

So I was reading through Javascript: The Definitive Guide and was reviewing this simple function:

function merge(o, p){
    for(prop in p){
        if(o.hasOwnProperty[prop]) continue;
        o[prop] = p[prop];
    }
    return o;
}

Seems simple enough, but when I run it it does not work unless I change o.hasOwnProperty[prop] to o.hasOwnProperty(prop).

This makes sense to me since hasOwnProperty is a method. Does this mean that this is just a mistake in the book? I'm reading the 6th edition, and this is printed on page 127 for those interested.

I suspect it is, but I just want to be sure there's not something strange about this function that I'm just not aware of that would make it work.

like image 451
Aweary Avatar asked Sep 19 '26 10:09

Aweary


1 Answers

Does this mean that this is just a mistake in the book?

Yes. That's really surprising.

o.hasOwnProperty[prop] is valid code, just not what Flanagan meant to use there. (It looks for a property with the name from the prop variable on the hasOwnProperty function object.)

Please tell me he declared prop somewhere as well. It's not declared in your quoted code, thus making the code seem to fall prey to The Horror of Implicit Globals.

like image 169
T.J. Crowder Avatar answered Sep 21 '26 01:09

T.J. Crowder



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!