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
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']);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With