0

こんにちは、jQuery ライブラリ 1.9 を使用して、JavaScript でよりオブジェクト指向の方法で作業することを学ぼうとしています。小さなプロジェクトで、このオブジェクトのスコープを変更する必要があります。ここに私の html があります。

<div id="contact">
<h2>Contact Me</h2>
<form action="#">
    <ul>
        <li>
            <label for="name">Name: </label>
            <input name="name" id="name">
        </li>

        <li>
            <label for="email">Email Address: </label>
            <input name="email" id="email">
        </li>

        <li>
            <label for="comments">What's Up?</label>
            <textarea name="comments" id="comments" cols="30" rows="10"></textarea>
        </li>
        <li>
            <input type="submit" value="Submit">
        </li>
    </ul>
</form>

そして、ここに私のjavascriptがあります

var contactForm = {
    contact : $('div#contact'),

    init : function(){
        this.contact.hide();
        $('<button></button>' , { 
            text : "Display Contact"
        }).insertAfter('article')
          .on('click' , this.show);
    },

    show : function(){
       $.proxy(contactForm , this)
       this.contact.slideDown();

    }
};

contactForm.init();

問題は show メソッドにあります。 $.proxy() を使用して「this」のスコープを設定できることはわかっています。しかし、 $.proxy を設定した後でも、「this」キーワードはまだボタン。

この「this」キーワードが「contactForm」オブジェクトを参照するようにするにはどうすればよいですか

4

3 に答える 3

0

これは機能するはずです:

.on('click', $.proxy(this.show, this));

そして表示:

show: function() {
   this.contact.slideDown();
}
于 2013-02-09T20:50:44.080 に答える
0

Your error is here:

.on('click' , this.show)

although this refers to this.show, it doesn't set the context to this when show is subsequently invoked as an event handler. You've got a function reference, but it ends up detached from the object which originally contained it.

You should use:

.on('click', $.proxy(this.show, this))

and remove the $.proxy call from within .show

Note that $.proxy() is intended to return a new function reference which when called will always have the given context. It does nothing to the current function's context.

于 2013-02-09T20:51:46.233 に答える
0

プロキシに関するドキュメントを読んでも、現在のメソッドの「this」コンテキストは変更されません。プロキシのシグネチャは、プロキシが$.proxy( myFunction, thisVar )関数を返し、myFunction実行時にmyFunctionこの値がを参照することを意味しthisVarます。

これで問題は解決しますか?

これは、show関数を次のようなものに変更することを意味します。

show : function(){
   $.proxy( function(){ this.slideDown() }, contactForm )();

}

これがどのように機能するかの簡単な例です

 f = $.proxy( function(){ console.log(this.msg); } , { msg: "hello world" });
 f(); // ==> should log to console "hello world"  

これが実際の動作を確認するためのフィドルです

関数にパラメーターを渡すこともできます。例えば:

 f = $.proxy( function(msg){ console.log([this,msg]); }, { topic:"my topic" } )
 f("hello world");

これが実際に動作していることを確認するには、フィドルを参照してください。

最後になりましたが、これは私が提案したように動作するコードのフィドルです。

于 2013-02-09T20:38:00.093 に答える