ES6 CLASS 가 위 챗 애플 릿 에서 의 응용 인 스 턴 스
3881 단어 ecmascript자바 script애플 릿
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 와 마찬가지 로 '클래스' 내부 에서
get
와 set
키 워드 를 사용 하여 특정한 속성 에 대해 저장 함수 와 수치 함 수 를 설정 하여 이 속성의 액세스 행 위 를 차단 할 수 있 습 니 다.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
}
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
JS 및 임시 제안의 날짜Javascript에서 날짜를 처리하는 것 자체가 고통스러울 수 있기 때문에 커뮤니티에서 , , , 및 기타 훌륭한 작업을 수행하는 라이브러리를 만들었습니다! 그러나 무엇보다도 먼저 이 노인과 아마도 다른 모든 사람...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.