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

これはうまくいくようです:

<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 に答える
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 に答える
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 に答える