質問

私は次の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ではなく、構文エラーのコレクションです。

使用する = 変数を割り当てるとき、および : 単純なオブジェクトの内部では、単純なオブジェクトや機能を混同しないでください。コンマを忘れないでください。 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
    };
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top