问题
今天我们来解析一下jQuery的基础架构原理,大家一起来研究吧~~
解决
首先,$(...)本身就是一个函数调用,所以它一定是个函数。
接着,既然$(...)返回值后面可以有各种方法(插件),那么$(...)的返回值一定是个new处理的对象实例。
最后,如果要实现$(...)可以作为对象传递,也可以作为数组传递,就要重写对象实例的prototype的方法。
!function(W, d){
if(!W.document) throw new Error("tfhtml requires a window with a document");
return d(W);
}(window, function(W){
// 这里实现 $(...)
var F = function(e){
return new F.fn.init(e);
};
// 这里是fn对象
F.fn = {
// 这里是jQuery的构造器
init : function(e){
}
};
// 初始化 F.fn 得到 F.fn.init 的示例
F.fn.init.prototype = F.fn;
// F 复制全局变量 tfhtml
W.tfhtml = F;
// 直接定义属性
F.fn.tfhtml = "v1.0.0";
// 直接定义方法
F.fn.fun = function(){
console.log("fun");
};
return W.tfhtml;
});
console.log(tfhtml.fn.tfhtml);
console.log(tfhtml.fn.fun);
tfhtml(document).fun();