jquery版本: jquery-1.0.js
html:
<body>
<p>1</p>
<p>2</p>
</body>
html:
console.log("p",$("p"))
结果:
jQuery {0: p, 1: p, length: 2}
实现代码如下:
function jQuery(a, b) {
function jQuery(a, b) {
[].push.apply(this, [a, b]);
//核心代码让数组对象的this指向Jquery函数,Function实际上也是一个Object对象,
// 如果Function对象上找不到和数组对象同名函数,就会在Object对象上找
//这里产生的{}对象的length只和传入的[1,2]的length有关,这个也是jquery的巧妙之处
}
jQuery.prototype = {
a: function () {
alert("a");
return this;
},
b: function () {
alert("b");
return this;
}
};
return new jQuery(a, b);
}
console.log(jQuery(1, 2).a().b()); //结果:jQuery {0: 1, 1: 2, length: 2}