Calling one method from another in JS
-
30-09-2019 - |
Pergunta
I have the following snippet of 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
}
}
How would I call Notify from ShipProduct?
Solução
That is not JS, that is a collection of syntax errors.
Use =
when assigning variables, and :
inside simple objects, don't confuse simple objects and functions, don't forget commas, and don't prefix property names with 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();
Outras dicas
This example looks fine except for the first line, that colon should be an equal sign.
The problem, I'm guessing, has to do with how you're calling ShipProduct
. If you're doing it like this, everything should work:
var customer = new Customer();
customer.ShipProduct();
However if you detach the method and call it directly, it won't work. Such as:
var customer = new Customer();
var shipMethod = customer.ShipProduct;
shipMethod();
This is because JavaScript relies on the dot notation accessor to bind this
. I'm guessing that you're passing the method around, perhaps to an Ajax callback or something.
What you need to do in that case it wrap it in a function. Such as:
var customer = new Customer();
var shipMethod = function() {
customer.shipMethod();
};
... later, in some other context ...
shipMethod();
This seems to work:
<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>
How about:
var Customer = function() {
var notify = function() {
...
};
var shipProduct = function() {
...
notify(...);
...
};
return {
notify: notify,
shipProduct: shipProduct
};
}
This assumes that you want to expose both functions -- if notify
is only used by Customer
internally, then there's no need to expose it, so you would instead return like so:
return {
shipProduct: shipProduct
};