0
此代码示例推导,如果你看到的代码中,B.prototype的doSomething()
方法是调用A.protoype的doSomething()
同时将B的this
OBJ从Mozilla原型继承返回值
扭捏。那么为什么这个代码的输出从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)
谢谢,就是这样。傻我。 – Minty 2015-03-02 18:51:27