function Animal(name,numLegs){
this.name = name;
this.numLegs = numLegs}
Animal.prototype.sayName = function(){
console.log("Hi my name is " + this.name );}
var penguin = new Animal("Captain Cook", 2);
penguin.sayName();
for (var prop in penguin){
console.log(prop);}
penguin.hasOwnProperty('sayName')
name
numLegs
sayName
=> false
hasOwnProperty() The hasOwnProperty() method returns a boolean indicating whether the object has the specified property as its own property (as opposed to inheriting it).
In general, hasOwnProperty() is the right choice most of the time, because you avoid issues with special keys, like constructor . A good rule of thumb is that if you're looking to see whether an object has a property, you should use hasOwnProperty() .
The prototype property allows you to add properties and methods to any object (Number, Boolean, String and Date, etc.). Note − Prototype is a global property which is available with almost all the objects. Use the following syntax to create a Boolean prototype.
There are mainly two methods to check the existence of a key in JavaScript Object. The first one is using “in operator” and the second one is using “hasOwnProperty() method”. Method 1: Using 'in' operator: The in operator returns a boolean value if the specified property is in the object.
When JavaScript is looking for a property, it first looks into the object itself. If it isn't there, it normally keeps walking up the prototype chain. hasOwnProperty
exists to check only the object itself, explicitly not walking up the prototype chain. If you want to check if a property exists at all, checking everything in the prototype chain, use the in
operator:
'sayName' in penguin // => true
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