前言
Class 是ES6 引入的最重要的特性之一,在没有class之前,我们只能通过原型链来模拟类。
点击查看ES6 类的详细内容:https://blog.csdn.net/Charissa2017/article/details/103939865
在ES5中,如果函数要作为构造函数使用,也就是要通过new实例化,就需要将函数的首字母大写。
function Box(){
//...这里相当于ES6类中的constructor
}
Box.s=3;//相当于ES6中给Box添加静态属性
Box.prototype.a=1;//相当于ES6中给Box添加动态属性
Box.prototype.abc=function(){//相当于ES6中给Box添加动态方法
console.log(this.a);
}
// 实例化,通过new的方法将函数作为类来实现一个实例
var b=new Box();
var c=new Box();
b.a=10;
console.log(b);//打印结果如下图
b.abc();//打印a=10
c.abc();//打印a=1
//如果对象下有对象属性,直接调用对象属性,如果没有对象属性,就查找它的原型链中离他最近原型属性
打印b的结果:
案例:给元素添加设置宽高背景的方法
HTMLElement.prototype.width=function(value){
if(value.constructor===Number) value+="px";
this.style.width=value;
return this;
}
HTMLElement.prototype.height=function(value){
if(value.constructor===Number) value+="px";
this.style.height=value;
return this;
}
HTMLElement.prototype.bg=function(value){
this.style.backgroundColor=value;
return this;
}
var div=document.createElement("div");
div.width(100).height(100).bg("red");
document.body.appendChild(div);
案例:给元素添加设置宽高背景的属性
Object.defineProperties(HTMLElement.prototype,{
w:{
set:function(value){
if(value.constructor===Number) value+="px";
this._w=value;
this.style.width=value;
},
get:function(){
return parseFloat(this._w);
}
},
h:{
set:function(value){
if(value.constructor===Number) value+="px";
this._h=value;
this.style.height=value;
},
get:function(){
return parseFloat(this._h);
}
},
bg:{
set:function(value){
this._bg=value;
this.style.backgroundColor=value;
},
get:function(){
return this._bg;
}
}
})
var p=document.createElement("p");
p.w=50;
p.h=50;
p.bg="green";
document.body.appendChild(p);
案例:实现柯里化函数
Function.prototype.currying=function(){
var self=this;
var list=[];
return function(){
if(arguments.length>0){
list=list.concat.apply(list,arguments);
return arguments.callee;
}
return self.apply(null,list);
}
}
function getSum(){
return Array.from(arguments).reduce((value,item)=>value+item);
}
var fns=getSum.currying();
fns(1,3,5);
fns(6,8,2);
var s=fns();
console.log(s);//25