经典面试题系列(5):ES5函数转化ES6的class

1,094 阅读1分钟

1.题目要求( 基于ES6中的class重构下面的代码)

function Modal(x,y){
    this.x=x;
    this.y=y;
}
Modal.prototype.z=10;
Modal.prototype.getX=function(){
    console.log(this.x);
}
Modal.prototype.getY=function(){
    console.log(this.y);
}
Modal.n=200;
Modal.setNumber=function(n){
    this.n=n;
};
let m = new Model(10,20);

2.实现方法

class Modal {
	// 构造函数:this.xxx=xxx 都是给实例设置的私有的属性
	constructor(x, y) {
		this.x = x;
		this.y = y;
	}
	// 这样写也是给实例设置私有的属性
	// z = 10;  //=>this.z=10

	// 直接写方法就是扩展到原型上的
	getX() {
		console.log(this.x);
	}
	getY() {
		console.log(this.y);
	}

	// 把类作为对象设置私有的属性方法
	static n = 200;
	static setNumber(n) {
		this.n = n;
	}
}
//给类的原型上添加基本数据类型
Modal.prototype.z = 10;

let m = new Modal(10, 20);