Skip navigation

JavaScript keeps giving shock to me even after using, learning since so long years! I just came to know that hasOwnProperty method is not guarded by the JavaScript language. Users can override it. Below code demonstrates how to override, consequences and work around.

//
var foo = {
    // overriding foo's default hasOwnProperty method
    hasOwnProperty: function() {
        return false;
    },
    bar: 'rajakvk'
};

foo.hasOwnProperty('bar'); // false always

// using hasOwnProperty of of object and setting this to foo
({}).hasOwnProperty.call(foo, 'bar'); // true

// or use hasOwnProperty from the 
// Object prototype for this purpose
Object.prototype.hasOwnProperty.call(foo, 'bar'); // true
//
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: