简体   繁体   中英

function instance hasOwnProperty() confusion

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

http://jsfiddle.net/5FzBQ/

Since the doOtherStuff function is defined directly on the b 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.

See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM