此代码示例是从Mozilla
派生和调整的如果您看到代码,则B.prototype的doSomething()
方法在应用B' s doSomething()
obj时调用A.protoype' s this
。那么为什么这段代码的输出从B.prototype而不是A.prototype返回?可能是我在这里遗漏了一些东西,但无法弄清楚原因。
function A(a) {
this.varA = a;
}
// What is the purpose of including varA in the prototype when A.prototype.varA will always be shadowed by
// this.varA, given the definition of function A above?
A.prototype = {
varA: null, // Shouldn't we strike varA from the prototype as doing nothing?
// perhaps intended as an optimization to allocate space in hidden classes?
// https://developers.google.com/speed/articles/optimizing-javascript#Initializing instance variables
// would be valid if varA wasn't being initialized uniquely for each instance
doSomething: function(a) {
return "DoSomething From A"
}
}
function B(a, b) {
A.call(this, a);
this.varB = b;
}
B.prototype = Object.create(A.prototype, {
varB: {
value: null,
enumerable: true,
configurable: true,
writable: true
},
doSomething: {
value: function() { // override
A.prototype.doSomething.apply(this, arguments);
return "DoSomething From B" // call super
// ...
},
enumerable: true,
configurable: true,
writable: true
}
});
B.prototype.constructor = B;
var b = new B();
b.doSomething(7)
答案 0 :(得分:1)
调用A.prototype.doSomething
,您只是对A
原型上的方法返回的值没有做任何事情。
A.prototype.doSomething.apply(this, arguments);
返回“来自A的DoSomething”并且该值被丢弃return "DoSomething from B"
将返回b.doSomething(7)
。将您的return
更改为console.log
,您会看到它的效果与您预期的一样,您会收到A
消息,然后会收到B
消息