JS之理解ES6聲明類class原理

ES6 class原理

1.經過構造函數聲明類es6

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聲明類segmentfault

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...this

  • 分析:①People是一個類,也是一個函數;②constructor是一個對象指向的是People函數,該函數還掛了nameage屬性;③將say函數掛載People的原型上。prototype

  • 代碼code

    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);
         }
       }   
    })
相關文章
相關標籤/搜索