2010-08-20 83 views
0

我的JS從調用另一個方法JS

var Customer : function() 
{ 
    this.ShipProduct : function() 
    { 
     //Logic for shipping product. If shipping successful, notify user 
     //Here I am trying to call Notify 
     //this.Notify(); // does not work 
    } 

    this.Notify = function() 
    { 
     //Logic for notify 
    } 
} 

下面的代碼片段我怎麼會叫從ShipProduct通知?

+0

您可以嘗試通過移動ShipProduct方法上面的方法通知嗎? – InSane 2010-08-20 22:31:08

+0

@In Sane - 不,這不起作用 – Nick 2010-08-23 14:15:19

回答

8

這不是JS,那是一個語法錯誤的集合。

使用=在簡單對象中分配變量和:時,不要混淆簡單對象和函數,不要忘記逗號,也不要將屬性名稱用this.作爲前綴。

var Customer = { 
    ShipProduct : function() 
    { 
     //Logic for shipping product. If shipping successful, notify user 
     //Here I am trying to call Notify 
     this.Notify(); // this does work 
    }, 
    Notify: function() 
    { 
     //Logic for notify 
    } 
} 

Customer.ShipProduct(); 
+0

我沒有創建一個對象。我想創建這個對象的多個實例,我的理解是你使用的語法創建了一個關聯的函數數組。我想要做一些像var customer = new Customer(); – Nick 2010-08-23 14:13:44

0

如何:

var Customer = function() { 
    var notify = function() { 
     ... 
    }; 
    var shipProduct = function() { 
     ... 
     notify(...); 
     ... 
    }; 
    return { 
     notify: notify, 
     shipProduct: shipProduct 
    }; 
} 

這是假設要公開這兩種功能 - 如果notify僅用於Customer內部,那麼就沒有必要揭露它,這樣你反而會迴歸像這樣:

return { 
     shipProduct: shipProduct 
    }; 
1

這似乎工作:

<html> 
<head> 
<script type = "text/javascript" language = "JavaScript"> 
var Customer = function(){ 
    this.ShipProduct = function(){ 
     alert("hey!"); 
     this.Notify(); 
    }; 

    this.Notify = function(){ 
     //Logic for notify 
     alert("notify"); 
    }; 
}; 
</script> 
</head> 
<body> 
<script type = "text/javascript" language = "JavaScript"> 
var cust = new Customer(); 
cust.ShipProduct(); 
</script> 
</body> 
</html> 
+0

這對我不起作用 – Nick 2010-08-21 03:24:40

1

這個例子看起來很好,除了第一行,冒號應該是一個等號。

問題,我猜,與你打電話給ShipProduct的方式有關。如果你正在做它像這樣,就可以工作了:

var customer = new Customer(); 
customer.ShipProduct(); 

不過,如果你分離的方法,並直接調用它,它不會工作。如:

var customer = new Customer(); 
var shipMethod = customer.ShipProduct; 
shipMethod(); 

這是因爲JavaScript的依賴點符號訪問到綁定this。我猜你正在傳遞方法,可能是Ajax回調或其他東西。

你在這種情況下需要做什麼,它將它包裝在一個函數中。如:

var customer = new Customer(); 
var shipMethod = function() { 
    customer.shipMethod(); 
}; 
... later, in some other context ... 
shipMethod();