inheritance - JavaScript: Why does the Object.hasOwnProperty method behave like this? -
inheritance - JavaScript: Why does the Object.hasOwnProperty method behave like this? -
my understanding object.hasownproperty method checks if object has property name of it's own, meaning non-inherited property. mean function should homecoming false whenever property a. doesn't exist, or b. if it's inherited.
correct me if i'm wrong, unless doesn't utilize classical inheritance, doesn't bar inherit foo in code below? why hasownproperty method returning true when propname property inherited property? did wrong here?
also, how utilize hasownproperty on foo object? code here returns false when checking the foo object.
function foo() { this.propname = 'test'; } var bar = new foo(); console.log(bar.hasownproperty('propname')); // returns true console.log(foo.hasownproperty('propname')); // returns false
the initial code sample equivalent to:
function foo() { } var bar = new foo(); bar.propname = 'test'; console.log(bar.hasownproperty('propname')); // returns true console.log(foo.hasownproperty('propname')); // returns false this why bar.hasownproperty('propname') returns true (the property has been explicitly set on bar object), , foo.hasownproperty('propname') returns false (the property has not been set on foo @ all, neither on foo object nor prototype).
the hasownproperty check used this:
function foo() { this.propname = 'test'; } foo.prototype.inheritedprop = 'test'; var bar = new foo(); console.log(bar.hasownproperty('propname')); // returns true console.log(bar.hasownproperty('inheritedprop')); // returns false javascript inheritance hasownproperty
Comments
Post a Comment