ES6 CLASS 가 위 챗 애플 릿 에서 의 응용 인 스 턴 스

ES6 CLASS 기본 용법
class Point {
  constructor(x, y) {
    this.x = x;
    this.y = y;
  }

  toString() {
    return '(' + this.x + ', ' + this.y + ')';
  }
}

1.1 constructor 방법constructor 방법 은 클래스 의 기본 방법 으로 new 명령 을 통 해 대상 인 스 턴 스 를 생 성 할 때 이 방법 을 자동 으로 호출 합 니 다.하나의 클래스 는 constructor 방법 이 있어 야 합 니 다. 명시 적 정의 가 없 으 면 빈 constructor 방법 이 기본적으로 추 가 됩 니 다.
class Point {
}

//    
class Point {
  constructor() {}
}

위의 코드 에 서 는 빈 클래스 Point 를 정의 합 니 다. 자 바스 크 립 트 엔진 은 자동 으로 빈 constructor 방법 을 추가 합 니 다.
1.2 클래스 의 인 스 턴 스
클래스 를 생 성 하 는 인 스 턴 스 의 쓰기 도 ES5 와 마찬가지 로 new 명령 을 사용 합 니 다.앞에서 말 했 듯 이 더하기 new 를 잊 어 버 리 면 함수 처럼 호출 Class 하면 오류 가 발생 할 수 있 습 니 다.

class Point { // ...
} //   
var point = Point(2, 3); //   
var point = new Point(2, 3);

1.3 수치 함수 (getter) 와 저장 함수 (setter)
ES5 와 마찬가지 로 '클래스' 내부 에서 getset 키 워드 를 사용 하여 특정한 속성 에 대해 저장 함수 와 수치 함 수 를 설정 하여 이 속성의 액세스 행 위 를 차단 할 수 있 습 니 다.
class MyClass {
  constructor() {
    // ...
  }
  get prop() {
    return 'getter';
  }
  set prop(value) {
    console.log('setter: '+value);
  }
}

let inst = new MyClass();

inst.prop = 123;
// setter: 123

inst.prop
// 'getter'

1.4 
this 의 지향
클래스 의 방법 내부 에 this 가 포함 되 어 있 으 면 기본적으로 클래스 를 가리 키 는 인 스 턴 스 입 니 다.하지만 이 방법 을 단독으로 사용 하면 잘못 보고 할 수 있 으 니 조심해 야 한다.
class Logger {
  printName(name \= 'there') { this.print(\`Hello ${name}\`);
  }

  print(text) {
    console.log(text);
  }
}

const logger \= new Logger();
const { printName } \= logger;
printName(); // TypeError: Cannot read property 'print' of undefined

위의 코드 에서 printName 방법 중의 this 은 기본적으로 Logger 클래스 의 실례 를 가리킨다.그러나 이 방법 을 추출 하여 단독으로 사용 하면 this 이 방법 이 실 행 될 때 있 는 환경 (class 내부 가 엄격 한 모델 이기 때문에 this 가 실제 가리 키 는 것 은 undefined 이 므 로 print 방법 을 찾 지 못 해 오 류 를 보고 합 니 다.
ES6 CLASS 가 위 챗 애플 릿 에서 의 응용 인 스 턴 스
//index.js

import {Card} from './Card/Card.js'; //  
const app = getApp()
Page({
  //     
  data: {
    cards:{},
  },
  onLoad: function () {
    var url = "https://app.******.com/submit_ajax.ashx?action=APP_GetCardslist";
    var param = {uid:'37906'};
    var carcard = new Card(url,param);

    var that = this;
    //        ,             
    // var cardData = carcard.getCardData();
    carcard.getCardData((data)=>{
      //        
      if (data.status == '1') {
        that.setData({
          cards: data.result
        })
        console.log(that.data.cards);
      } else {
        wx.showToast({
          title: data.msg,
          icon:'none'
        })
      }
    })
  },
  
})
var util = require("../../../utils/util.js");
//  Card  
class Card {
  //    ,         
  constructor(url,parameter) {
    this.url = url;
    this.parameter = parameter;
  }
  
  getCardData(cb) {
    this.cb = cb;
    util.http(this.url,this.parameter,"POST",this.processCarCardData.bind(this));
  }

  processCarCardData(data) {
    if (!data) {
      return;
    }
    this.cb(data);
  }

}
//class      ,  export       
export {Card}
//util.js

function http(url,parameter,method, callback) {
  wx.request({
    url: url,
    method: method,
    data:{parameter},
    header: { "Content-type": "application/json" },
    success: function (res) {
      callback(res.data);
    },
    fail: function () {
      console.log("error");
    }
  });
}

module.exports \= {
  http:http
}

좋은 웹페이지 즐겨찾기