既然doOtherStuff函数是直接在b实例上定义的,而不是在prototype链中“上面”定义的(比如base甚至Object),那么为什么b.hasOwnProperty('doOtherStuff')返回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 truehttp://jsfiddle.net/5FzBQ/
发布于 2014-01-10 15:11:06
因为
doOtherStuff函数是直接在b实例上定义的
这不是真的;您在cls.prototype中定义了该属性。
hasOwnProperty()只有在编写this.property = ... (或b.property)时才会返回true。
发布于 2014-01-10 15:19:01
doOtherStuff不是直接在b上定义的,b从它的原型继承doOtherStuff。hasOwnProperty区分直接在对象上定义的属性与从原型继承的属性,而in没有。
https://stackoverflow.com/questions/21047716
复制相似问题