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?
hasOwnProperty() The hasOwnProperty() method returns a boolean indicating whether the object has the specified property as its own property (as opposed to inheriting it).
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.
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.
hasOwnProperty() should be O(1) , as it is a key lookup, but it will be implementation specific.
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")
.
hasOwnProperty
expects the property name as a string, so it would be shape1.hasOwnProperty("name")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With