tags:

views:

211

answers:

4
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 its returning false. Whats the correct behavior?

+4  A: 

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

SLaks
Thanks for correcting the mistake.
Thiyaneshwaran S
A: 

Try this:

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

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]);
 }
Ernelli
yes, it works. thanks
Thiyaneshwaran S
A: 

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

Pablo Cabrera
missed the "string" part. thanks.
Thiyaneshwaran S
A: 

hasOwnProperty has string parameter.

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")); // alert true

}

works fine.

Best development http://vitana-group.com/

Universal