In operator vs hasOwnProperty property

In yesterday’s post about the in operator, Bertrand mentioned that it would be interesting to show the differences between the in operator and the hasOwnProperty method defined on the Object “type”. As always, he’s right and I guess that I should write up a small post explaining the difference between these two.

Both of them check if a property belongs to an object, but there’s an important difference between them (besides the fact that in is an operator and hasOwnProperty is a property which references a function): the in operator will check the property name against the properties of the object +  the properties defined on the prototype object; on the other hand, the hasOwnProperty property will only check that name agains the properties of the object.

Here’s a really simple example which tries to show the main differences between these two:

var User = function(name) {
    this.name = name;
}
User.prototype.printInfo = function() {
    alert(this.name);
}
var user = new User("luis");
alert("printInfo" in user); //true :checks prototype
alert(user.hasOwnProperty("printInfo"));//false

From an usage point of the view, that’s really main difference between the operator and the method. Since hasOwnProperty is a property of object, there are a couple of things you should keep in mind:

  • every object has access to it (because all JavaScript objects end up “inheriting” the Object’s type prototype functions);
  • its use might be “compromised” by a redefinition of that property (which can be done by adding a property to the new object with that name or by changing the prototype’s hasOwnProperty property to a new value – which, btw, could even be a non function value!)

And that’s it for now. Keep tuned for more on JavaScript.

Advertisements

~ by Luis Abreu on August 28, 2009.

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: