Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

hasOwnProperty in JavaScript

Tags:

javascript

Consider:

function Shape() {     this.name = "Generic";     this.draw = function() {         return "Drawing " + this.name + " Shape";     }; }  function welcomeMessage() {     var shape1 = new Shape();     //alert(shape1.draw());     alert(shape1.hasOwnProperty(name));  // This is returning false } 

.welcomeMessage called on the body.onload event.

I expected shape1.hasOwnProperty(name) to return true, but it's returning false.

What is the correct behavior?

like image 522
Thiyaneshwaran S Avatar asked Apr 08 '10 13:04

Thiyaneshwaran S


People also ask

What is hasOwnProperty in JavaScript?

hasOwnProperty() The hasOwnProperty() method returns a boolean indicating whether the object has the specified property as its own property (as opposed to inheriting it).

Why do we use hasOwnProperty?

hasOwnProperty determines if the whole property is defined in the object itself or in the prototype chain. In other words: do the so-called check if you want properties (either with data or functions) coming from no other place than the object itself.

Has its own property JS?

The hasOwnProperty() method in JavaScript is used to check whether the object has the specified property as its own property. This is useful for checking if the object has inherited the property rather than being it's own.

What is the time complexity of hasOwnProperty?

hasOwnProperty() should be O(1) , as it is a key lookup, but it will be implementation specific.


2 Answers

hasOwnProperty is a normal JavaScript function that takes a string argument.

When you call shape1.hasOwnProperty(name) you are passing it the value of the name variable (which doesn't exist), just as it would if you wrote alert(name).

You need to call hasOwnProperty with a string containing name, like this: shape1.hasOwnProperty("name").

like image 111
SLaks Avatar answered Oct 13 '22 05:10

SLaks


hasOwnProperty expects the property name as a string, so it would be shape1.hasOwnProperty("name")

like image 42
Pablo Cabrera Avatar answered Oct 13 '22 06:10

Pablo Cabrera