JavaScript的对象模型是基于原型实现的,特点是简单,缺点是理解起来比传统的类-实例模型要困难,最大的缺点是继承的实现需要编写大量代码,并且需要正确实现原型链。
接下来我们来看一下更简单的实现方法:
新的关键字class
从ES6开始正式被引入到JavaScript中。class
的目的就是让定义类更简单。
我们首先用函数实现Student
的方法:
function Student(name)
{
this.name = name;
}
Student.prototype.hello = function ()
{
alert('Hello, ' + this.name + '!');
}
如果用新的class
关键字来编写Student
,可以这样写:
class Student
{
constructor(name)
{
this.name = name;
}
hello() {
alert('Hello, ' + this.name + '!');
}
}
比较一下就可以发现,class
的定义包含了构造函数constructor
和定义在原型对象上的函数hello()
最后,创建一个Student
对象代码:
var xiaoming = new Student('小明');
xiaoming.hello();