2019-05-05 20:47:14
在ES5中,我们写一个类,通常是这么写的
function Person(name,age){ this.name = name; this.age = age; } /** * es5中的模拟面向对象的类的方法 写法1 Person.prototype.showName = function(){ return "名字为:"+this.name; } Person.prototype.showAge = function(){ return "年龄为:"+this.age; }*/ /** * es5中的模拟面向对象的类的方法 写法2 * */ Object.assign(Person.prototype,{ showName(){ return "名字为:"+this.name; }, showAge(){ return "年龄为:"+this.age; } }); var p1 = new Person('tom',18); console.log(p1.showName());//名字为:tom console.log(p1.showAge());//年龄为:18
在ES6中,我们可以这样写
//ES6中的类(类名大小写都可以,推荐使用规范按照首字母大写) class Person{ constructor(name,age){//构造方法(函数),每new一个新对象,自动执行 // console.log(`构造函数执行了,${name},${age}`);//构造函数执行了,Lucy,18 this.name = name; this.age = age; } showName(){ return `名字为:${this.name}`; } showAge(){ return `年龄为:${this.age}`; } } let p1 = new Person('Lucy',18); console.log(p1.showName(),p1.showAge());//名字为:Lucy 年龄为:18
//ES6中的类(赋给一个变量或常量,类名大小写都可以,推荐使用规范首字母大写) const Person = class{ constructor(name,age){//构造方法(函数),每new一个新对象,自动执行 // console.log(`构造函数执行了,${name},${age}`);//构造函数执行了,Lucy,18 this.name = name; this.age = age; } showName(){ return `名字为:${this.name}`; } showAge(){ return `年龄为:${this.age}`; } } let p1 = new Person('Lucy',18); console.log(p1.showName(),p1.showAge());//名字为:Lucy 年龄为:18
注意:
(1).ES6里面Class没有提升(例如ES5中的函数有提升到顶部的作用)
(2).ES6中的this,首先来看一下ES5中矫正this的几个方法
(2.1) fn.call(this指向谁,args1,args2...);
(2.2) fn.apply(this指向谁,[args1,args2...]);
(2.3) fn.bind();(React中经常会用到)
其中,(2.1) fn.call和(2.2) fn.apply都会在矫正this的时候,方法(函数)会调用一次
class Person{ constructor(){ this.name = 'jason'; this.showName = this.showName.bind(this);//矫正this } showName(){ console.log('this:',this);//this: Person {name: "jason", showName: function} return `名字为:${this.name}`; } } let p1 = new Person(); let {showName} = p1; console.log(showName());//名字为:jason
class Person{ constructor(name){ this.name = name; } get aaa(){ return `获取aaa的名字,值为${this.name}`; } set aaa(val){ console.log(`设置aaa的名字,值为${val}`); } } let p1 = new Person('jack'); console.log(p1.aaa);//获取aaa的名字,值为jack p1.aaa = 'luke';//设置aaa的名字,值为luke
class Person{ constructor(){ } showName(){ return '这是showName方法'; } static aaa(){ return '这是静态方法'; } } let p1 = new Person(); console.log(p1.showName());//这是showName方法 console.log(Person.aaa());//这是静态方法
先来回顾一下ES6之前的继承写法
1.原型链继承
//父类 Animal.prototype.eat = function(food) { console.log(this.name + '正在吃' + food); } function Animal(name) { this.color = ['green','red','blue'