0

我有以下 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 调用 Notify?

4

4 回答 4

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();
于 2010-08-20T22:31:28.267 回答
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();
于 2010-08-20T23:08:54.230 回答
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>
于 2010-08-20T22:41:01.043 回答
0

怎么样:

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

这假设您想要公开这两个函数 - 如果notify仅在Customer内部使用,则无需公开它,因此您将改为返回:

    return {
        shipProduct: shipProduct
    };
于 2010-08-20T22:35:00.380 回答