function Student(name) {
this.name = name;
}
Student.prototype.hello = function () {
alert('Hello, ' + this.name + '!');
}
用class
class Student {
constructor(name) {
this.name = name;
}
hello() {
alert('Hello, ' + this.name + '!');
}
}
class继承
class PrimaryStudent extends Student {
constructor(name, grade) {
super(name); // 记得用super调用父类的构造方法!
this.grade = grade;
}
myGrade() {
alert('I am at grade ' + this.grade);
}
}
需要通过super(name)来调用父类的构造函数,否则父类的name属性无法正常初始化
不是所有的主流浏览器都支持ES6的class。可以试试Babel这个工具。
练习
'use strict';
class Animal {
constructor(name) {
this.name = name;
}
}
class Cat extends Animal{
constructor(name){
super(name);
}
say(){
return 'Hello, '+this.name+'!';
}
}
// 测试:
var kitty = new Cat('Kitty');
var doraemon = new Cat('哆啦A梦');
if ((new Cat('x') instanceof Animal) && kitty && kitty.name === 'Kitty' && kitty.say && typeof kitty.say === 'function' && kitty.say() === 'Hello, Kitty!' && kitty.say === doraemon.say) {
alert('测试通过!');
} else {
alert('测试失败!');
}