javascript:定义"this"在函数的上下文中

javascript: Defining "this" in the context of a function

本文关键字:quot 上下文 函数 javascript this 定义      更新时间:2023-09-26

当jQuery调用一个函数作为引发事件的事件处理程序时,jQuery以某种方式能够在它调用的函数上下文中定义"this"。在下面的例子中,jQuery将this定义为被点击的dom元素。

<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如何做到这一点?我想复制这种行为为我自己的自定义框架。

Function有两个方法可以使用:call和apply。使用这两种方法,将想要用于this的对象作为第一个参数传递。使用call时,附加参数将依次传递:

functionName.call(this, arg1, arg2);

使用apply,传入参数数组:

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

或者,您可以传递一个实际的参数对象:

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

您可以使用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)更改为您想要的任何元素

都是闭包

Javascript在定义像this这样的变量时使用了闭包。

所以你可以这样做:

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

所以如果你这样做了:

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

而:

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

常规的旧javascript/html也可以。

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

不知道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'