Javascript 范围因传递回调函数的方式而异

Javascript scope different depending how you pass callback function

本文关键字:方式 函数 回调 范围 Javascript      更新时间:2023-09-26
function DoSomething()
{
     var scope = this;
}

请考虑以下调用它的方法:选项 1:

var self= this;
$someElement.change(self.DoSomething);

选项 2:

var self= this;
$someElement.change(function(){self.DoSomething();});
为什么当触发

更改事件时,第一行代码导致scope成为触发事件的元素,但第二行代码导致与self相同但第二行scope

由于我不明白这里的概念,所以我很难谷歌正确的搜索词。

jQuery在原始元素的上下文中调用给定的函数。

选项 1:

您已将self.DoSomething作为函数传递。
jQuery将在$someElement的上下文中调用self.DoSomething

执行以下代码:

var self = this;
self.DoSomething.call($someElement);
function DoSomething()
{
    // this = $someElement
    var scope = this;
}

DoSomething this内等于被叫方 - $someElement

选项 2:

您已将匿名函数作为函数传递。
jQuery将在$someElement上下文中调用匿名函数:

var self = this; 
function() {
    self.DoSomething();
}.call($someElement);
function() {
    // this = $someElement, as well
    self.DoSomething(); // LOOK! You call self's method. Not within any context
}
function DoSomething()
{
    // default function call, default this is presented
}