4

私はnode.jsを使用しており、express.jsに基づいてプログラミングしています。util.inheritsJavaScriptで継承を実装するために使用しようとしました。私が試したことは次のとおりです。

//request.js
function Request() {
    this.target = 'old';
    console.log('Request Target: ' + this.target);
}

Request.prototype.target = undefined;
Request.prototype.process = function(callback) {
    if (this.target === 'new')
       return true;

    return false;
}

module.exports = Request;

//create.js
function Create() {
    Create.super_.call(this);
    this.target = 'new';
}

util.inherits(Create, Request);

Create.prototype.process = function(callback) {
    if (Create.super_.prototype.process.call(this, callback)) {
        return callback({ message: "Target is 'new'" });
    } else {
        return callback({ message: "Target is not 'new'" });
    }
}

module.exports = Create;

//main.js
var create = new (require('./create'))();
create.process(function(msg) {
    console.log(msg);
});

私のシナリオは次のとおりです。

私はRequest基本クラスとCreate子クラスを持っています。リクエストには、コンストラクターtargetで初期化するフィールドがあります。oldRequest

ここで、最初にコンストラクターをCreate呼び出してから、フィールドを で初期化するクラス オブジェクトを作成します。のプロセス関数を呼び出すと、 のメッセージが返されるはずですが、別のメッセージが返されます。RequesttargetnewCreatetarget is 'new'

これについて同様のスレッドを検索しましたが、すべて私が試したものです! 誰が何が間違っていたのか説明できますか?

前もって感謝します :)

4

1 に答える 1

6

util.inherits本当に厄介ですsuper_...とにかく、これはうまくいくはずです:

 Create.super_.prototype.process.call(this, callback);

でも本当に、

 var super_ = Request.prototype;

そして、構文はほとんど便利になります。

 super_.process.call(this, callback);
于 2013-08-05T16:24:27.143 に答える