https://github.com/JsAaron/jQuery
https://git.oschina.net/studentzxc/loop-test
http://www.imooc.com/code/3248
jQuery的无new构建原理
函数aQuery()内部首先保证了必须是通过new操作符构建。这样就能保证当前构建的是一个带有this的实例对象,既然是对象我们可以把所有的属性与方法作为对象的key与value的方式给映射到this上,所以如上结构就可以模拟出jQuery的这样的操作了,即可通过索引取值,也可以链式方法取值,但是这样的结构是有很大的缺陷的,每次调用ajQuery方法等于是创建了一个新的实例,那么类似get方法就要在每一个实例上重新创建一遍,性能就大打折扣,所以jQuery在结构上的优化不仅仅只是我们看到的,除了实现类数组结构、方法的原型共享,而且还实现方法的静态与实例的共存,这是我们之后将会重点分析的。
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style type="text/css">
div{
30px;
height: 10px;
float:left;
}
</style>
<script src="jquery-2.1.1.js"></script>
</head>
<body>
<button id="test1">jQuery[0]</button>
<button id="test2">jQuery.get</button>
<button id="test3">aQuery[0]</button>
<button id="test4">aQuery.get</button>
<p id="book">book</p>
<div id="show1"></div>
<div id="show2"></div>
<div id="show3"></div>
<div id="show4"></div>
<script>
var aQuery = function(selector){
if(!(this instanceof aQuery)){
return new aQuery(selector)
}
var elem = document.getElementById(/[^#].*/.exec(selector)[0]);
this.length = 1;
this[0] = elem;
this.context = document;
this.selector = selector;
this.get = function(num){
return this[num];
}
return this;
}
$("#test1").click(function() {
$('#show1').append($('#book')[0])
})
$("#test2").click(function() {
$('#show2').append($('#book').get(0))
})
$("#test3").click(function() {
$('#show3').append(aQuery('#book')[0])
})
$("#test4").click(function() {
$('#show4').append(aQuery('#book').get(0))
})
</script>
</body>
</html>