ES5的类和原型

前言

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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值