Chiamare un metodo da un altro in JS
-
30-09-2019 - |
Domanda
Ho il seguente frammento di 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
}
}
Come chiamerei una notifica da ShipProduct?
Soluzione
Non è JS, che è un insieme di errori di sintassi.
Usa =
quando si assegnano le variabili, e :
all'interno di oggetti semplici, non oggetti non confondere semplici e funzioni, non dimenticate le virgole, e fare i nomi di proprietà non prefisso con 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();
Altri suggerimenti
Questo esempio cerca bene, tranne per la prima linea, che i due punti dovrebbe essere un segno di uguale.
Il problema, sto cercando di indovinare, ha a che fare con il modo si sta chiamando ShipProduct
. Se stai facendo in questo modo, tutto dovrebbe funzionare:
var customer = new Customer();
customer.ShipProduct();
Tuttavia, se si Stacca il metodo e chiamarlo direttamente, non funzionerà. Come ad esempio:
var customer = new Customer();
var shipMethod = customer.ShipProduct;
shipMethod();
Questo perché JavaScript si basa sulla notazione del punto di accesso per bind this
. Sto indovinando che si sta passando il metodo intorno, forse per un callback Ajax o qualcosa del genere.
Quello che dovete fare in quel caso si avvolge in una funzione. Come ad esempio:
var customer = new Customer();
var shipMethod = function() {
customer.shipMethod();
};
... later, in some other context ...
shipMethod();
Questo sembra funzionare:
<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>
Come su:
var Customer = function() {
var notify = function() {
...
};
var shipProduct = function() {
...
notify(...);
...
};
return {
notify: notify,
shipProduct: shipProduct
};
}
Questo presuppone che si desidera esporre entrambe le funzioni - se notify
è usato solo da Customer
internamente, allora non c'è bisogno di esporre, in modo che avrebbe invece tornare in questo modo:
return {
shipProduct: shipProduct
};