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