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);
         }
       }   
    })  
     
     
    原文作者:何凯
    原文地址: https://segmentfault.com/a/1190000010361428
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞