在JS中调用另一种方法
-
30-09-2019 - |
题
我有以下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中致电通知?
解决方案
那不是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();
其他提示
除了第一行外,这个示例看起来不错,那位结肠应该是一个相等的符号。
我猜这个问题与您的打电话方式有关 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();
这似乎有效:
<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>
怎么样:
var Customer = function() {
var notify = function() {
...
};
var shipProduct = function() {
...
notify(...);
...
};
return {
notify: notify,
shipProduct: shipProduct
};
}
这假设您想公开这两个功能 - 如果 notify
仅由 Customer
在内部,无需公开它,因此您会像这样返回:
return {
shipProduct: shipProduct
};
不隶属于 StackOverflow