学习MDN:JavaScript中的继承,摘录如下:
在经典的面向对象语言中,您可能倾向于定义类对象,然后您可以简单地定义哪些类继承哪些类(参考C++ inheritance里的一些简单的例子),JavaScript使用了另一套实现方式,继承的对象函数并不是通过复制而来,而是通过原型链继承(通常被称为 原型式继承 —— prototypal inheritance)。
下面通过代码演示。
创建一个Person()构造函数,包含一些属性。方法放到原型上。
function Person(first, last, age, gender, interests) {
this.name = {
first,
last
};
this.age = age;
this.gender = gender;
this.interests = interests;
};
Person.prototype.greeting = function() {
alert('Hi! I\'m ' + this.name.first + '.');
};
这时需要创建一个Teacher()构造函数,继承Person()的所有属性,同时满足:
(1)新增一个自身属性subject代表教师学科;
(2)更新greeting()方法。
如何操作?
1.首先定义Teacher()构造函数
function Teacher(first, last, age, gender, interests, subject) {
Person.call(this, first, last, age, gender, interests);
this.subject = subject;
}
上面用call()方法调用了Person(),第一个参数指明了运行这个函数时想对“this”指定的值,也就是说,您可以重新指定您调用的函数里所有“this”指向的对象。
2.让Teacher()从Person()的原型对象里继承共有属性
Teacher.prototype = Object.create(Person.prototype);
//注意将constructor属性指向Teacher
Teacher.prototype.constructor = Teacher;
3.在Teacher()的原型对象上定义新的greeting()方法
Teacher.prototype.greeting = function() {
var prefix;
if(this.gender === 'male' || this.gender === 'Male' || this.gender === 'm' || this.gender === 'M') {
prefix = 'Mr.';
} else if(this.gender === 'female' || this.gender === 'Female' || this.gender === 'f' || this.gender === 'F') {
prefix = 'Mrs.';
} else {
prefix = 'Mx.';
}
alert('Hello. My name is ' + prefix + ' ' + this.name.last + ', and I teach ' + this.subject + '.');
};
创建Teacher()对象实例
var teacher1 = new Teacher('Dave', 'Griffiths', 31, 'male', ['football', 'cookery'], 'mathematics');
teacher1.name.first;
teacher1.interests[0];
teacher1.bio();
teacher1.subject;
teacher1.greeting();
完。