js继承封装

大厂必面,js继承封装

  • 话不多说,直接上代码
Function.prototype.extends = function (superClass) {
       //声明一个变量,将原有原型对象存储起来
        var o = this.prototype;
        function F() {}
        F.prototype = superClass.prototype;
        this.prototype=new F();
        //获取当前类所有属性名
        var names=Object.getOwnPropertyNames(o);
        //遍历所有属性名,获取属性名的属性描述
        for(var i=0;i<names.length;i++){
            var desc=Object.getOwnPropertyDescriptor(o,names[i]);
            //将当前原型与被继承的原型对象结合
            Object.defineProperty(this.prototype,names[i],desc);
        }
        //将继承的类,定义为当前原型链上一个超类
        this.prototype.superClass=superClass;
        //判断当前原型对象原型是否为该原型对象,不是则赋值为对应的原型对象
        if(this.prototype.constructor!==this){
            Object.defineProperty(this.prototype,"constructor",{
                value:this
            })
        }
         //判断当前继承对象原型是否为继承的原型对象,不是则赋值为对应的原型对象
        if(superClass.prototype.constructor!==superClass){
            Object.defineProperty(superClass.prototype,"constructor",{
                value:superClass
            })
        }
      };
  • 简单示例
  function CheckBox(){

      }
      CheckBox.prototype={
          a:1,
          b:function(){

          }
      }

      function Radio(){
          this.superClass.apply(this,arguments);
      }

      Radio.prototype={
          c:10,
          d:function(){

          }
      }
      Radio.extends(CheckBox);

      var r=new Radio();
      console.log(r);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值