Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using apply() in IIFE

Tags:

javascript

I'm trying to use apply() within IIFE. I get an error 'intermediate value is not a function' where am I going wrong ?

var Person = {
  getFullName : function(firstName, lastName) {
      return firstName + ' ' + lastName;
  }
}

/* IIFE - using apply */

(function(firstName, lastName) {
   getName = function(){
    console.log("From IIFE..");
    console.log(this.getFullName(firstName, lastName));
} 
  getName();
}).apply(Person, ['John', 'Doe']);  

Plnnkr : http://plnkr.co/edit/77db8Mu4i9RXGqt26PAP?p=preview

like image 271
user1184100 Avatar asked Jan 06 '23 13:01

user1184100


1 Answers

The problem is with ;, in your code the Person object syntax is not terminated, and the IIFE is considered as continuation of that.

Read: Automatic semicolon insertion

If you look at external libraries, their IIFE statement starts with a ;, that is used to escape from this scenario.

Also note that, inside your getName function this does not refer to the Person object, you need to either use a closure variable or pass the value for this manually.

var Person = {
  getFullName: function(firstName, lastName) {
    return firstName + ' ' + lastName;
  }
}

/* IIFE - using apply */

;
(function(firstName, lastName) {

  var self = this;
  var getName = function() {
    console.log("From IIFE..");
    console.log(self.getFullName(firstName, lastName));
  }
  getName();
}).apply(Person, ['John', 'Doe']);
like image 128
Arun P Johny Avatar answered Jan 11 '23 23:01

Arun P Johny