2011-04-18 63 views
0

當jQuery調用函數作爲引發事件的事件處理函數時,jQuery以某種方式能夠在它調用的函數的上下文中定義「this」。在下面的例子中,jQuery將其定義爲被點擊的dom元素。javascript:在函數的上下文中定義「this」

<input id="someButton" type="button" value="click me!"/> 
<script type="text/javascript"> 
    $("#someButton").click(EventHandler); 
    function EventHandler() 
    { 
      alert($(this).attr("id")); //This raises an alert message "someButton" 
    } 
</script> 

jQuery如何做到這一點?我想複製此行爲爲我自己的自定義框架。

回答

0

不知道什麼jQuery使用,但有一個bind功能:

var regularFunc = function() { 
    console.log(this); 
}; 

var boundFunc = regularFunc.bind(123); 

regularFunc(); // logs whatever 'this' is at time it is called (e.g. 'window') 
boundFunc(); // logs 123 at all times since that is specified to be 'this' 
0

其全部關閉。

當定義像this這樣的變量時,Javascript使用閉包。

所以你可以做這樣的事情:

var myFuncs = { 

    func1: function(){ 
     this.func2 = function() { alert('hello');} 
     return this; 
    }, 
    func2: function(){alert('HI')} 

} 

所以,如果你這樣做:

myFuncs.func1().func2(); // alerts 'hello' 

而:

myFuncs.func2(); // alerts 'HI' 
3

一個Function有兩種方法,您可以使用:callapply。使用這兩種方法時,將想要使用的對象作爲第一個參數傳遞給this。使用call,額外的參數傳遞一個接一個:

functionName.call(this, arg1, arg2); 

使用apply,傳遞參數數組:

functionName.apply(this, [arg1, arg1]); 

或者,你可以通過一個實際的參數對象:

function someFunction() 
{ 
    functionName.apply(this, this.arguments); 
} 
2

您可以使用callapply JavaScript方法:

function myFunction() { 
    // you want "this" to be your element 
} 

var element = SOMEDOMELEMENT; 

myFunction.call(element, /* add other comma-separated arguments here, if any */); 

myFunction.apply(element, /* add an array of arguments here, if any */); 

當使用call和apply時,它將函數內的上下文(this)更改爲您希望它的任何元素。

0

普通的舊javascript/html也可以。

<button id='something' onclick='alert(this.id);'>Click me</button> 
相關問題