Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/384.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 在JS中从一个方法调用另一个方法_Javascript_Javascript Framework_Javascript Objects - Fatal编程技术网

Javascript 在JS中从一个方法调用另一个方法

Javascript 在JS中从一个方法调用另一个方法,javascript,javascript-framework,javascript-objects,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.N

我有下面的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?

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

Use=在分配变量时,和:在简单对象中,不要混淆简单对象和函数,不要忘记逗号,也不要在属性名称前加上前缀

那么:

var Customer = function() {
    var notify = function() {
        ...
    };
    var shipProduct = function() {
        ...
        notify(...);
        ...
    };
    return {
        notify: notify,
        shipProduct: shipProduct
    };
}
这假设您希望公开这两个函数—如果notify仅由客户在内部使用,则不需要公开它,因此您可以这样返回:

    return {
        shipProduct: shipProduct
    };
这似乎有效:

<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>

这个例子看起来不错,除了第一行,冒号应该是等号

我猜,问题在于你如何称呼ShipProduct。如果你是这样做的,一切都应该正常:

var customer = new Customer();
customer.ShipProduct();
但是,如果分离该方法并直接调用它,它将无法工作。例如:

var customer = new Customer();
var shipMethod = customer.ShipProduct;
shipMethod();
var customer = new Customer();
var shipMethod = function() {
    customer.shipMethod();
};
... later, in some other context ...
shipMethod();
这是因为JavaScript依赖于点符号访问器来绑定它。我猜您正在传递该方法,可能是传递给Ajax回调或其他什么

在这种情况下,您需要做的是将其封装在函数中。例如:

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

你能试着把notify方法移到ShipProduct方法的上方吗?@在正常情况下-不,这不起作用,我没有创建一次性对象。我想创建这个对象的多个实例,我的理解是,您使用的语法创建了一个关联的函数数组。我想做一些事情,比如var customer=新客户;