在JS中调用另一个方法

时间:2010-08-20 22:29:37

标签: javascript javascript-framework javascript-objects

我有以下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 个答案:

答案 0 :(得分:8)

这不是JS,这是语法错误的集合。

在分配变量时使用=,在简单对象中使用:,不要混淆简单的对象和函数,不要忘记逗号,也不要在属性名称前添加{{1} }。

this.

答案 1 :(得分: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>

答案 2 :(得分:1)

这个例子看起来很好,除了第一行,冒号应该是一个等号。

我猜,这个问题与你如何打电话ShipProduct有关。如果你这样做,一切都应该有效:

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

但是,如果你分离方法并直接调用它,它将无效。如:

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

这是因为JavaScript依赖于 bind this的点符号访问器。我猜你正在传递方法,也许是传递给Ajax回调等等。

在这种情况下你需要做什么将它包装在一个函数中。如:

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

答案 3 :(得分:0)

怎么样:

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

这假设您要公开这两个函数 - 如果notify仅在Customer内部使用,那么就不需要公开它,所以你会这样返回:

    return {
        shipProduct: shipProduct
    };
相关问题