理解"this"在上下文中的功能



我已经尽力理解了这一点,但无法理解为什么'this'在第一个代码中不起作用,而在第二个代码示例中起作用。

第一个(此处不起作用(

$('#' + ID).parent().siblings().each(function() {
selectChildren();
});
function selectChildren() {
$(this).children('.left-links-dashboard').css({
'color': 'grey'
});
//this one doesn't work..why ????
}

在这里,selectChildren((函数有一个参数,当调用函数时,这个被传递给函数,它就工作了。。

第二次

$('#' + ID).parent().siblings().each(function() {
selectChildren(this);
});
function selectChildren(esd) {
$(esd).children('.left-links-dashboard').css({
'color': 'grey',
'font-weight': '400'
});
$(esd).children('.left-links-dashboard').children('i').removeClass('fa-arrow-circle-right').addClass('fa-angle-right');
}

已经阅读了stackoverflow、MDN和其他资源,但不明白为什么第二个代码示例有效。任何解释都会对我很有帮助。谢谢

this表示当前函数引用

但是在您的第一个代码中,CCD_ 2在包装器CCD_,如果你想让第一个代码工作,你可以这样做


$('#' + ID).parent().siblings().each(selectChildren); 
// I removed the anonymouse function to set the reference of the jquery element directly to selectChildren function 
function selectChildren() {
$(this).children('.left-links-dashboard').css({
'color': 'grey'
});
//this one doesn't work..why ????
}  
javascript中的this是函数所有者的上下文。看见https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this

您的第一个示例意味着被调用的函数由window对象所有。如果你想以"jquery方式"使用你的功能:

$(this(.selectChildren((

然后研究编写jquery插件:https://learn.jquery.com/plugins/basic-plugin-creation/

最新更新