代码之家  ›  专栏  ›  技术社区  ›  Billy ONeal IS4

如何在Javascript中重新定义“this”?

  •  5
  • Billy ONeal IS4  · 技术社区  · 14 年前

    我有一个函数是JQuery事件处理程序。因为它是一个JQuery事件处理程序,所以它使用 this 变量引用调用它的对象(对于该库是正常的)。

    不幸的是,此时我需要手动调用该方法。我该怎么做

    示例代码:

    function performAjaxRequest() {
        //Function which builds AJAX request in terms of "this"
    }
    
    function buildForm(dialogOfForm) {
        var inputItem;
        dialogOfForm.html('...');
        dialogOfForm.dialog('option', 'buttons', {
            "Ok" : performAjaxRequest
        });
        inputItem = dialogOfForm.children(':not(label)');
        //Redirect enter to submit the form
        inputItem.keypress(function (e) {
            if (e.which === 13) {
                performAjaxRequest(); //Note that 'this' isn't the dialog box
                                      //as performAjaxRequest expects here, it's
                                      //the input element where the user pressed
                                      //enter!
            }
        }
    }
    
    5 回复  |  直到 14 年前
        1
  •  8
  •   Reigel Gallarde    14 年前

    如果 dialog this 然后:

    performAjaxRequest.apply(dialog, []); 
    // arguments (instead of []) might be even better
    

    否则,在jQuery中,您可以简单地调用 trigger 方法设置要设置为的元素

    比如说,你想 click 事件发生在按钮上,你需要它发生 现在

    $("#my_button").trigger("click");
    

    你的 #my_button 点击 将调用处理程序,并且 将设置为 #我的按钮

    如果需要调用具有不同 ... 例如,用 call apply 你的职责。

    // Call
    my_function.call(object_to_use_for_this, argument1, argument2, ... argumentN);
    
    // Apply
    my_function.apply(object_to_use_for_this, arguments_array);
    

    见: A List Apart's Get Out of Binding Situations

        2
  •  12
  •   Chuck    14 年前

    call 方法。

    someFunction.call(objectToBeThis, argument1, argument2, andSoOnAndSoOn);
    
        3
  •  4
  •   meder omuraliev    14 年前

    你在找。。

    functionRef.apply( objectContext, arguments);
    
        4
  •  1
  •   Quickredfox    14 年前

    你当然应该学会掌握 call() apply()

    在jQuery中,有 $.proxy . 在pure js中,您可以使用以下内容重新创建这种漂亮的特性:

    function proxyFn( fn , scope ){
      return function(){
         return fn.apply(scope,arguments);
      }
    }
    

    var myFunctionThatUsesThis = function(A,B){
      console.log(this,arguments); // {foo:'bar'},'a','b'
    };
    
    // setTimeout or do Ajax call or whatever you suppose loses "this"
    
    var thisTarget = {foo: 'bar'};
    setTimeout( proxyFn( myFunctionThatUsesThis, thisTarget) , 1000 , 'a', 'b' );
    
    // or...
    
    var contextForcedCallback = proxyFn( myAjaxCallback , someObjectToBeThis );
    performAjaxRequest(myURL, someArgs, contextForcedCallback );
    

    如果你不滥用它,这是一个肯定的消防工具,永远不会失去“这个”的范围。

        5
  •  0
  •   fullstacklife    14 年前

    使用闭包

    var that = this;