簡體   English   中英

node.js / javascript —嵌套的回調

[英]node.js / javascript — nested callbacks

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”時將'this.b'視為'undefined'?

謝謝!

您傳遞給該方法的匿名回調函數會創建一個新的作用域,因此,當您在回調函數中說this.b時,它不再是相同的b ,而是一個新的b

解決此問題的一種常見方法是在回調之外創建對您要訪問的this的引用:

var self = this;

然后,您可以在回調中引用self.b

首先是一個很好的閱讀

對於您的特定示例,您可以這樣編碼,保存對MyClass實例的this的引用:

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);
    });
};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM