在JavaScript中,prototype对象是实现面向对象的一个重要机制。
每个函数就是一个对象(Function),函数对象都有一个子对象 prototype对象,类是以函数的形式来定义的。prototype表示该函数的原型,也表示一个类的成员的集合。
父类
function People(name, age, sex) {
this.name = name;
this.age = age;
this.sex = sex;
}
People.prototype.sayHello = function () {
console.log('你好,我是' + this.name + ',我今年' + this.age + '岁了。');
}
People.prototype.sleep = function () {
console.log(this.name + '开始睡觉zzzzzz');
}
子类
关键语句,实现继承:Student.prototype = new People();
function Student(name, age, sex, school, studentNumber) {
this.name = name;
this.age = age;
this.sex = sex;
this.school = school;
this.studentNumber = studentNumber;
}
// 关键语句,实现继承
Student.prototype = new People();
// 重写父类的同名方法
Student.prototype.sayHello = function () {
console.log('敬礼!你好,我是' + this.name + ',我今年' + this.age + '岁了。');
}
Student.prototype.study = function () {
console.log(this.name + '正在学习');
}
var zhangsan = new Student('张三', 16, '男', 'XX高级中学', 10306);
zhangsan.sayHello();
zhangsan.sleep();
输出结果:
敬礼!你好,我是张三,我今年16岁了。
张三开始睡觉zzzzzz