我是 JavaScript 编程新手。我编写了一个 IIFE,它将帮助我提高理解。我的目的是定义一个 $ 函数,在调用时会将其自身称为构造函数。运行代码时,它会生成错误“递归过多”。我不知道问题出在哪里。
(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);
最佳答案
var $ = function () {
return new $(); //this line generates an error 'Too much recursion.'
}
此函数重复调用自身,这就是您看到 Too much recursion.
错误的原因。您无法区分常规函数调用和 new
调用。
My intention is to define a $ function that when called will call itself as a constructor.
最简单的方法是显式检查:
var $ = function $() {
if(!(this instanceof $)) return new $();
// ... from this point on, behave as if called via new
}
关于javascript - IIFE 引发错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18945573/