连缀介绍:一行代码同时设置一个或多个节点两个或两个以上的操作。
代码介绍:
Base.getId('box').style['background']='black';
Base.getId('box').style['color']='red';
Base.getId('box').innerHTML='post';
简化代码为一行代码
window.οnlοad=function(){Base.getId('box').css('color','red').html('post').click(function(){alert('a');});}
改造Base对象
var Base = function () {
return new $();
}
function $() {
//容纳外部的对象。类似于面向对象的属性。
this.element = null;
//获取ID节点
this.getId = function (id) {
this.element=document.getElementById(id));
return this;
};
}
//支持扩展,添加function
//设置CSS
$.prototype.css = function (attr, value) {
this.element.style[attr] = value;
return this;
}
//设置HTML
$.prototype.html = function (str) {
this.element.innerHTML = str;
return this;
}
//设置onclick
$.prototype.click = function (fn) {
this.element.onclick = fn;
return this;
}
总结:
设置一个第三方对象来完成对另一个对象的装饰。自我感觉像装饰模式。另外就是this的使用,在这里对this指代哪个对象呢?它和指代window的this有什么区别呢?