Reputation: 1309
I'm new to JavaScript programming.I wrote an IIFE that will help me improve my understand. My intention is to define a $ function that when called will call itself as a constructor. When the code is run, it generates an error 'Too much recursion'. I don't know what the problem is.
(function() {
//check the global host object
var root = this;
var inside = "inside";
var $ = function () {
return new $(); //this line generates an error 'Too much recursion.'
}
$.check = function(obj) {
console.log(inside);
}
//add the $ to global object
root.$ = $;
}).call(this);
var ins = $();
console.log(ins);
Upvotes: 0
Views: 104
Reputation: 22905
var $ = function () {
return new $(); //this line generates an error 'Too much recursion.'
}
This function is repeatedly calling itself, which is why you see the Too much recursion.
error. You aren't distinguishing between a regular function call and a new
call.
My intention is to define a $ function that when called will call itself as a constructor.
The simplest way is to explicitly check this:
var $ = function $() {
if(!(this instanceof $)) return new $();
// ... from this point on, behave as if called via new
}
Upvotes: 1
Reputation: 4718
It's because you have created an infinite loop. By using parenthesis when returning your new var instance you are recursively calling that function with no parameters. I'm not sure what you are trying to accomplish, but you might want to have $ create a new object "{}" instead and then you can extend methods off of that reference. Look into singleton patterns, that will allow you to create a new instance of something.
*edit, and just to be clear your problem doesn't have anything to do with it being an IIFE, you would encounter this same error anywhere you tried to call a new function on itself in this manner.
Upvotes: 0
Reputation: 1074495
this line generates an error 'Too much recursion.'
Right. You have a function assigned to the $
symbol which calls the function assigned to the $
symbol. So each call (whether direct or via new
) will run the code in that function, which makes another call to it, and so on until you exceed the engine's willingness to recurse. To avoid that, have $
do something else.
Upvotes: 0