Since the doOtherStuff
function is defined directly on the b
instance, and not "above" it in the prototype chain (like on base
or even Object
), why does b.hasOwnProperty('doOtherStuff')
return false?
var base = (function () {
var cls = function () { };
cls.prototype.doStuff = function () {
console.log('dostuff');
};
return cls;
})();
var child = (function () {
var cls = function () {
base.call(this);
};
cls.prototype = Object.create(base.prototype);
cls.prototype.constructor = child;
cls.prototype.doOtherStuff = function () { // <--
console.log('doOtherStuff');
}
return cls;
})();
var b = new child();
console.log(b.hasOwnProperty('doOtherStuff'), 'doOtherStuff' in b); //false true
Since the
doOtherStuff
function is defined directly on theb
instance
That's not true; you defined that property in cls.prototype
.
hasOwnProperty()
will only return true if you write this.property = ...
(or b.property
).
doOtherStuff
is not defined directly on b
, b
inherits doOtherStuff
from its prototype. hasOwnProperty
distinguishes between properties defined directly on the object versus properties inherited from the prototype whereas in
does not.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.