Bracket notation with Object.hasOwnProperty?

So I was reading Javascript: The Definitive Guide and was looking at 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 doesn't 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 am reading 6th edition and it is printed on page 127 for those interested.

I suspect it is, but I just want to make sure there is nothing weird about this feature, that I just don't know what would make it work.

+3


source to share


1 answer


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

Yes. This is really amazing.



o.hasOwnProperty[prop]

- valid code, just not the one Flanagan wanted to use there. (It looks for a property named from a variable prop

in a function object hasOwnProperty

.)

Please tell me what he announced prop

somewhere. It is not declared in your cited code, so the code seems to fall victim to the "Horror of Implicit Globals" .

+2


source







All Articles