在看jquery的时候我就在想,为什么会有这个符号来代替JavaScript很多方面的工作呢,那它是如何做到这一点的呢?首先我觉得作者一定跟我一样不想每次都写document.gelElementById这么长的单词,怎么办呢,我试试能不能简化一下子~
比如有个这样的需求,页面上有个隐藏的按钮,
<button id="button">点击我</button>
<img id="image" src="xxx.jpg">
这太简单了,一分钟就写出来了
var button = document.getElementById('button');
var image = document.getElementById('image');
button.onclick = function(){
image.style.display = 'none';
};
看着也不是很复杂嘛,但是我们改造一番,简化一下工作
var $ = function(id) {
return document.getElementById(id);
};
$("button").onclick = function() {
$("image").style.display = "none";
};
这里的$()就是最简单的包装器,只是返回的是原生的DOM对象
这个时候我们需要封装一下hide方法,不然老写xxx.style.display = "none"也要累死,首先我们可以拿最近学到的原型方法。
var $ = function(id) {
return document.getElementById(id);
};
HTMLElement.prototype.hide = function() {
this.style.display = 'none';
};
$('button').onclick = function() {
$('image1').hide();
$('image2').hide();
}
emmmm,似乎很好的工作了呢,到这里我们就收工了吗?好像还不行,HTMLElement兼容性不是很好,我们得再考虑考虑。
道格拉斯的object方法(等同于object.create方法)这个时候好像可以起到作用~
var F = function(id) {
this.element = document.getElementById(id);
};
F.prototype.hide = function() {
this.element.style.display = 'none';
};
document.getElementById('button').onclick = function() {
new F('image1').hide();
new F('image2').hide();
};
然后再修整一下子
var F = function(id) {
return this.getElementById(id);
};
F.prototype.getElementById = function(id) {
this.element = document.getElementById(id);
return this;
};
F.prototype.hide = function() {
this.element.style.display = "none";
};
new F("image").hide();
差不多ok了。什么?你要$,不要new F(id),好吧,请你往前面看第一步优化,
var $ = function(id) {
return new F(id);
};
好了 收工,回家睡觉~
网友评论