Tôi đang chơi với util.inherits
method from node.js và dường như không thể có được hành vi mong muốn.util.inherits - cách gọi phương thức siêu ví dụ?
var util = require("util");
function A() {
this.name = 'old';
}
A.prototype.log = function(){
console.log('my old name is: '+ this.name);
};
function B(){
A.call(this);
this.name = 'new';
}
util.inherits(B, A);
B.prototype.log = function(){
B.super_.prototype.log();
console.log('my new name is: ' + this.name);
}
var b = new B();
b.log();
Kết quả là:
my old name is: undefined
my new name is: new
Tuy nhiên những gì tôi muốn là:
my old name is: new
my new name is: new
tôi thiếu gì?
Cách khác: B.super_.prototype.log.call (this); – Klaasvaak
Btw cuộc gọi là sự lựa chọn tốt hơn .. http://jsperf.com/function-calls-direct-vs-apply-vs-call-vs-bind/6 – korCZis
Tôi thích sử dụng từ khóa 'this':' this .constructor.super_.prototype.log.call (this) ', do đó bạn không cần phải sử dụng tên lớp một lần nữa trong phương pháp – kit