var key="constructor";
var obj = {};
if(obj[key]) {
console.log("obj has property 'constructor'");
}
if(obj.hasOwnProperty(key)) {
console.log("obj has own property 'constructor'");
}else{
console.log("obj does not have own property 'constructor'");
}
Output:
obj has property 'constructor'
obj does not have own property 'constructor'
Explanation:
The code defines a variable `key` with the value "constructor" and an empty object `obj`.
It then checks if the object has a property with the name specified in `key` using
the `if(obj[key])` condition.
Since all objects in JavaScript inherit from `Object.prototype`,
the object has the 'constructor' property through its prototype chain.so object has property 'constructor' is printed.
Next, it checks if the object has its own property with the name specified in `key`
using the `obj.hasOwnProperty(key)` method.
Since the object does not have its own property named 'constructor',
the output "obj does not have own property 'constructor'" is printed.
No comments:
Post a Comment