2
function MyClass() {
    this.a = "me a";
    this.b = "me b";
};

MyClass.prototype.changeB = function(callback) {
    this.a = "now me A";
    doAnotherFunction(function(err, data) {
        this.b = "now me B";
    callback(null, this.b);});
};

function doAnotherFunction(callback) {
    callback(null, null);
};

main();

function main() {
    var myclass = new MyClass();
    myclass.changeB(function(err, data) {
    console.log("B: " + myclass.b + ", data: " + data);});
    console.log(JSON.stringify(myclass));
}


When this runs:
B: me b, data: now me B
{"a":"now me A","b":"me b"}

私はjavascriptとここに投稿するのが初めてです。

私の質問は、元の MyClass インスタンス化で「this.b」が変更されないのはなぜですか? ここで、javascript にブロック スコープがない (関数スコープのみ) を読みました。それが理由なら、なぜ「this.b」を「未定義」として扱わず、「now me B」に設定しないのでしょうか?

ありがとう!

4

2 に答える 2

2

ここから始めるのに良い読み物です。

this特定の例では、次のようにコーディングして、MyClassインスタンスの への参照を保存できます。

MyClass.prototype.changeB = function(callback) {
    var me = this;
    this.a = "now me A";
    doAnotherFunction(function(err, data) {
        me.b = "now me B";
        callback(null, me.b);
    });
};

提案に応じてbindを使用する例:

MyClass.prototype.changeB = function(callback) {
    this.a = "now me A";
    var fn = function(err, data) {
        this.b = "now me B";
        callback(null, this.b);
    });
    // the first parameter to bind will be the 'this'
    // visible from inside the function
    doAnotherFunction(fn.bind(this));
};

編集:あなたの例に何があったかを調べるthisには、いくつかのログを追加してみてください:

MyClass.prototype.changeB = function(callback) {
    var me = this;
    this.a = "now me A";
    doAnotherFunction(function(err, data) {
        // Use this['b'] notation to avoid errors using this.b,
        // if this.b doesn't already exist.
        console.log(me, typeof me, this, typeof this, this['b']);
        this.b = "now me B";
        callback(null, this.b);
    });
};
于 2013-04-26T21:28:33.153 に答える