80

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?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Thiyaneshwaran S
  • 1,137
  • 2
  • 10
  • 14
  • 6
    it requires a string, so `"name"` as opposed to `name` – AO_ Oct 17 '13 at 13:59
  • Possible duplicate of [javascript what is property in hasOwnProperty?](http://stackoverflow.com/questions/9396569/javascript-what-is-property-in-hasownproperty) – pathe.kiran Apr 28 '16 at 06:26

4 Answers4

157

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").

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
  • 1
    Don't forget to add the hasOwnProperty() returns a boolean value indicating the property (in this case name) specified exists or not – Mahesh Jamdade Feb 03 '19 at 14:28
19

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

Pablo Cabrera
  • 5,749
  • 4
  • 23
  • 28
3

Try this:

function welcomeMessage()
{
    var shape1 = new Shape();
    //alert(shape1.draw());
    alert(shape1.hasOwnProperty("name"));
}

When working with reflection in JavaScript, member objects are always refered to as the name as a string. For example:

for(i in obj) { ... }

The loop iterator i will be hold a string value with the name of the property. To use that in code you have to address the property using the array operator like this:

 for(i in obj) {
   alert("The value of obj." + i + " = " + obj[i]);
 }
Dor Cohen
  • 16,769
  • 23
  • 93
  • 161
Ernelli
  • 3,960
  • 3
  • 28
  • 34
2

hasOwnProperty() is a nice property to validate object keys. Example:

var obj = {a:1, b:2};

obj.hasOwnProperty('a') // true
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
KARTHIKEYAN.A
  • 18,210
  • 6
  • 124
  • 133