Tân
Tân

Reputation: 1

Why can't I use IIFE with "this"?

My test code:

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>

I'd reference Immediately-invoked function expression but it didn't mention about using this in this case.

My question is: Is there any way to use this as an element (this = $('.' + c)) in the example?

Upvotes: 0

Views: 689

Answers (2)

Alireza
Alireza

Reputation: 104760

You can use bind() or call() or apply() and pass 'this' through them as your scope changed for 'this'...

It's always a good practice using these functions in javascript, rather then attach it to the function...

The best option is call for your code...

(function() {
    this.css('color', '#f00')
}).call($('.' + c));

Also using click handler in your javascript, make your code much cleaner and can make your coding structure better, you also can use multiple selection in jQuery to keep HTML clean if needed more selectors handle this function...

Upvotes: 1

adeneo
adeneo

Reputation: 318252

Yes, there is a way to use this inside your IIFE's, you can bind the thisValue with bind() before calling the IIFE.

(function() {
    this.css('color', '#f00')
}).bind($('.' + c))();  

Upvotes: 2

Related Questions