我正在使用 Alex MacCaw 的 Javascript Web 应用程序研究原型(prototype)、类和模块化模式。几乎一切都清晰且解释良好,但是,我无法弄清楚用于初始化的空函数是如何工作的。如果您能解释其中的细微差别,无论它们有多复杂,我将不胜感激。
这是书中的示例:
(function($){
var mod = {};
mod.create = function(includes){
var result = function(){
this.init.apply(this, arguments);
};
result.fn = result.prototype;
result.fn.init = function(){};
result.proxy = function(func){ return $.proxy(func, this); };
result.fn.proxy = result.proxy;
result.include = function(ob){ $.extend(this.fn, ob); };
result.extend = function(ob){ $.extend(this, ob); };
if (includes) result.include(includes)
return result;
};
exports.Controller = mod;
})(jQuery);
从上面的代码中我了解到立即调用函数表达式(IIFE)用于保护作用域。然后定义 mod.create 构造函数,该函数返回带有所有类方法的结果对象。但是,我对以下的工作原理感到困惑:
this.init.apply(this, arguments);
result.fn.init = function(){};
我想我们将空的 init 函数应用于构造函数参数以允许新对象实例化或类似的东西。从下面的答案看来,init 函数接收了未定义数量的参数,但是什么参数呢?那些在实例化过程中使用的——上面代码中的包含?为什么这个函数是空的,调用时它会做什么?
最佳答案
this.init.apply(this, arguments);
基本上就是
this.init(arguments[0], arguments[1], ..., arguments[N]);
但是一旦我们不知道参数的确切数量 - 我们就使用 .apply()
使用示例:
var newConstructor = exports.Controller.create();
newConstructor.include({
init: function(a, b, c) { console.log(a, b, c, 'yay!'); }
});
var newInstance = new newConstructor(1, 2, 3);
关于javascript - 空函数 "function(){}"在JS对象构造函数中如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24261658/