JS之理解ES6声明类class原理

ES6 class原理

1.通过构造函数声明类

function People(name,age){
 this.name = name;
 this.age = age; 
}

People.prototype.say=function(){
    console.log("hello)}
    
People.see=function(){
    alert("how are you")}    

2.通过es6class声明类

class People{
  constructor(name,age){
     this.name = name;
     this.age = age}
     
  static see(){alert("how are you")}  }
  
  say(){console.log("hello");}}

3.es6 class原理

  • 首先得了解原型链的基础知识https://segmentfault.com/a/11...

  • 分析:①People是一个类,也是一个函数;②constructor是一个对象指向的是People函数,该函数还挂了nameage属性;③将say函数挂载People的原型上。

  • 代码

    let People = function(){ //第①步,创建People函数
     
     function People(name,age){//第②步,理解constructor就是指向People,People挂载着name和age两个属性
        this.name = name;
        this.age = age;}
       
     //将静态和动态的方法分别挂载在People的原型和People上。   
     creatClass(People,[{key:"say",value:function(){
         console.log(123)}}],[{key:"see",value:function(){
         alert("how are you")}}])  
         
     return People;}
     
    //这里的Constructor就是指的People  
    let creatClass = function({
      return function(Constructor,,protoProps,staticProps){
         //有原型上的方法挂载People.prototype上
         if(protoProps){defineProperties(Constructor.prototype,protoProps)}
          //有People对象上的方法挂载People上
         if(staticProps){defineProperties(Constructor,staticProps)}}
     
    //定义对象属性     
    let defineProperties =function(target, props) {
         for (var i = 0; i < props.length; i++) {
           var descriptor = props[i];
           Object.defineProperty(target, descriptor.key, descriptor);
         }
       }   
    })  
     
     
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值