2013-06-05 46 views
1

我在JS下一個功能:JS /使用對象,定義功能外

function status(){ 
    this.functionA = function(){} 
    //Some others function and fields 
} 

,我有另一個功能:

function create(root){ 
var server = libary(function (port) { 
    //Here some functions 
}); 
var returnValue = { 
    current:status(), 
    cur:function(port){ 
    current.functionA(); 
    }} 
return returnValue; 
} 

當我打電話current.functionA(),它說,當前是未定義。我怎樣才能撥打functionA()

回答

0

當你有一個函數,構造像status(),你將需要調用new它。我在這裏修改了部分代碼。

var returnValue = { 
    current: new status(), 
    cur:function(port){ 
    current.functionA(); 
    }} 
return returnValue; 
} 

只是爲了區分; create()不需要new語句,因爲實際上是在函數內部創建並返回一個要引用的對象。

+0

我按照你的說法嘗試,但它仍然給我,目前是未定義的 – user2450886

+1

@ user2450886在'​​'''裏面,你需要使用'this.current.functionA()',所以你引用'current'屬性'returnValue'。 (假設你調用'cur'作爲'returnValue'對象的一個​​方法,所以'this == returnValue')。 – apsillers

+0

@apsillers:我使用這個,但現在它給了我下一個錯誤:無法調用方法FunctionA() undefined – user2450886

0
function status(){ 
    this.functionA = function(){alert("functionA");} 
} 
function create(root){ 
    var returnValue = { 
     current:status.call(returnValue), 
     cur:function(port){ this.functionA(); }.bind(returnValue) 
    } 
    return returnValue; 
} 
create().cur(999); 

我糾正使用JavaScript「呼叫」和「綁定」方法,這是函數原型的一部分,你的問題。