我的测试代码:
var colorChanged = function (c) {
//valid syntax:
(function (x) {
x.css('color', '#f00')
})($('.' + c));
//invalid syntax:
(function (this) { //Uncaught SyntaxError: Unexpected token this
this.css('color', '#f00')
})($('.' + c));
};
<div class="demo">Div text</div>
<button onclick="colorChanged('demo')">Change color</button>
我会引用Immediately-invoked function expression但它没有提到在本例中使用 this
。
我的问题是:有没有办法在示例中使用 this
作为元素 (this = $('.' + c)
)?
最佳答案
是的,有一种方法可以在 IIFE 中使用 this
,您可以在调用 IIFE 之前使用 bind()
绑定(bind) thisValue
.
(function() {
this.css('color', '#f00')
}).bind($('.' + c))();
关于javascript - 为什么我不能将 IIFE 与 "this"一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34172799/