2014-03-04 53 views
2

下面是一個函數,它創建並對象並調用回調(不是確切的代碼,但類似的東西)。帶對象構造函數的Javascript回調

myObject = function(callback){ 

    var tmpThis = this; 
    this.accounts = []; 
    tmpThis.accounts[0] = 1; 
    tmpThis.accounts[1] = 2; 
    callback(); 
} 

function caller(){ 
    var newMyObject = new myObject(function() { 
     alert(newMyObject.accounts[1]); 
    }); 
} 

newMyObject在回調函數中未定義。有沒有一種方法可以訪問它?我讀過類似的問題,但沒有一個解釋了原因。

我可以通過將第二個參數中創建的對象傳遞迴回函數來修復它。但我認爲它是一種黑客而不是正確的方式。

+0

低劣的標題... – dezman

+0

標題編輯:) – Ish

回答

0

您可以使用this訪問新創建對象上下文中的回調,並使用call來調用回調。

myObject = function(callback){ 

    var tmpThis = this; 
    this.accounts = []; 
    tmpThis.accounts[0] = 1; 
    tmpThis.accounts[1] = 2; 
    callback.call(this); 
} 

function caller(){ 
    var newMyObject = new myObject(function() { 
     alert(this.accounts[1]); 
    }); 
} 
+0

感謝。這解決了問題。現在我必須將它應用於我在Angular中的真實應用程序。:( – Ish

0

newMyObject不知道newMyObject內部的參數傳遞給它。這將是未定義的。

換句話說,當alert(newMyObject.accounts[1]);運行時,new myObject定義的newMyObject不會存在。

function() { 
    alert(newMyObject.accounts[1]); 
} 

回調函數被傳遞到您的myObject的功能:當它被語句callback();,運行下面的代碼執行

newMyObject將是不確定的。你可以在你的myObject函數中使用alert(accounts[1])

您嘗試使用的模式通常不會執行函數回調。通常你會傳遞一個選項對象,這將用於定製myObject

目前尚不清楚你正在嘗試做什麼。

0

你可以試試這個:

function Application() { 

    var self = this; 

    myObject = function(callback){ 

     var tmpThis = this; 
     this.accounts = []; 
     tmpThis.accounts[0] = 1; 
     tmpThis.accounts[1] = 2; 
     callback(); 
    }; 

    function caller(){ 
     self.newMyObject = new myObject(function() { 
      alert(self.newMyObject.accounts[1]); 
     }); 
    } 
} 
0

呼叫尚未完成。將它設置爲下一個週期運行:

http://fiddle.jshell.net/gWUD9/

myObject = function(callback){ 

    var tmpThis = this; 
    tmpThis.accounts = []; 
    tmpThis.accounts[0] = 1; 
    tmpThis.accounts[1] = 2; 
    setTimeout(callback,1); 
} 

    var newMyObject = new myObject(function() { 
     alert(newMyObject.accounts[0]); 
    }); 
相關問題