ES5及ES6写对象的对比
经常会遇到需要在js 写 ES6 写对象,写了个实例供大家参考
ES5创建对象
// 类的基本写法
function Person(name, sex) {
var self = this;
this._name = name; // 外部可见的成员变量
this._sex = sex;
var no = Person.population; // 静态变量的引用
console.log('No.'+no);
var tmp = 0; // 私有的,外部不可见的成员量
// 成员方法
this.say = function() {
var str = '说唱中...';
sing(str); // 私有成员方法的调用
}
// 私有方法
function sing (str) {
console.log(str);
}
// 注意:以下面几点
// ps.1 私用方法中,调用外部可见的成员变量
function privateFun() {
// 使用this将报错,找不到方法
// this.say();
// 正确的姿势是
self.say(); // 为什么呢? 私用方法中使用 this 的含义是当前私用方法privateFun,
// 而当前privateFun私用方法中,并没用定义this.say(),这是因为在js中,每一个function实际就是一个类。
// 可以把function直接看成一个没外员可见的成员变量的方法
}
// ps.2 注意使用回调函数
function callbackFun() {
var timer = setInterval(function(){
// this.say(); // 错误的
self.say(); // 正确
}, 1000);
}
this.callbackFun1 = function() {
var timer = setInterval( function(){
// this.say(); // 错误的
self.say(); // 正确
} , 1000 )
}
this.callbackFun2 = function() {
// 注意,下面的箭头函数是ES6语法,需要浏览器支持(大多数浏览器已支持了)
let timer = setInterval( ()=>{
this.say(); // 正确
self.say(); // 正确
} , 1000 )
}
}
// js继承语法? 没有
// 静态成员的实现
Person.population = 0;
Person.born = function() {
Person.population +=1;
}
ES6创建对象
// 类的基本写法
class Person {
static population = 0 // 静态变量
// 构造方法
constructor(name, sex) {
this._name = name // 成员变量,外面可见的变量
this._sex = sex
const no = Person.population // 静态变量的引用
console.log('No.'+no)
}
// 成员方法
say= ()=> {
console.log('正在说...')
}
// 静态方法
static born = () => {
Person.population +=1
}
}
// 继承类
class Teacher extends Person {
constructor(name, sex) {
super(name, sex) // 调用父的构造方法
}
teaching = ()=>{
this.say() // 调用父方法
}
}