复习:类和对象
但是,之前我们只能生成一个匿名对象,或者使用JavaScript内置对象,我们好像不能自己定义一个类。
ES6终于提供了class关键字和其他面向对象的支持。我们可以这样声明一个Student类:
class Student { constructor(sname) { this.sname = sname; //this就是实例化之后的对象 } hello() { alert('Hello, ' + this.sname + '!'); //复习:用模板字符串改造 } }
class后面直接跟自定义(开发人员自己命名的)类名,花括号({})中的内容包括:
构造函数。构造函数可以有一个或多个参数,在对象生成时时调用:
var atai = new Student('atai');
演示:当用 new 来调用这个函数时,它就进入构造函数constructor,默认返回this。
hello()是实例方法,可以使用当前对象的属性(所以,一定要带上this,不信就试一试?)
演示:atai.name和atai.hello()
注意:
constructor(name) { this._name = name; return this; //默认省略 //可以new出一个匿名对象 //return { // age: 38 //}; ////这又是不行的,唉~~ //return '我就不是Student对象'; }
ES6的class本质上就是function。
function Student(name){ this.name=name; this.hello=function(){ alert('Hello, '+this.name+'!');} }
这不就是一个普通函数吗?
函数是普通函数,但当你用 new 来调用这个函数时,它就变成了一个构造函数,默认返回this
(所以,一定要带上this,不信就试一试?)
但是,不建议在函数中添加:
return this; //会是window对象
因为这样的话,new Student()没有问题,但Student()的时候,返回的就是window对象了……(详见:this总结)
演示:ES5的写法和ES6的class声明具有完全相同的效果在方法面前加上关键字static
static hello() { //注意这个this,代表的是当前类,不是当前实例哟 alert('Hello, ' + this.name + '!'); }该方法就只能用类而不是类的实例(instance)调用:
Student.hello();
演示:this.Name变成了Student(类名)
类中的方法可以互相调用。但是,在一个类中:
static方法体内不能调用实例方法(注意理解)
和C#不同:
getter和setter
get Name(){ return this.name.toUpperCase(); } set Name(value) { this.name = value; }
可以:
实现私有的hack方法:
function Student(name) { var _greet = "Hello, " return { name: name, hello: function () { alert(_greet + this.name + '!'); } } }
function LuckyStack() { var fee = 986, unit = '周'; return { cost: function () { console.log(`源栈收费:每${unit}${fee}元`); } } } var ls = LuckyStack(); console.log(ls.fee); //undefined,ls.fee不会被暴露 ls.cost(); //ls.cost()像一个public方法一样使用
Class表达式
把一个类赋值给一个变量
const Student = class DFG { constructor(name) { this.name = name; } hello() { alert(DFG.name + ' Hello, ' + this.name + '!'); } } var yf = new Student('yf');
类名(DFG)仅在class内部可用。如果内部没有使用,可以省略,而且可以写出立即执行的 Class
其他:
此前学习JavaScript面向对象的难点:你不知道JavaScript绕来绕去是为了什么……其实,她就是在模拟真正的“面向对象”语言。
说到底,还是没有class……有的是什么?
JavaScript只有一个class(对象模板):Object。
试试看:
console.log(typeof Student);
为什么呢?(原来是个“语法糖”)
作业:
作业点评:
多快好省!前端后端,线上线下,名师精讲
更多了解 加: