/**
* JavaScript(ES5)中实现继承的几种方法
*/
// 定义基类Person
function Person(name, age) {
this.name = name;
this.age = age;
}
// 共享数据
Person.prototype.LEGS_NUM = 2;
// 共享方法
Person.prototype.info = function () {
console.log('My name is ' + this.name + ' .I\'m ' + this.age + ' years old now');
};
Person.prototype.walk = function () {
console.log(this.name + ' is walking...');
};
// Student子类
function Student(name, age, className) {
// 调用父类
Person.call(this, name, age);
this.className = className;
}
// 1 方法一:Person.prototype直接赋值给Student.prototype
// Student.prototype = Person.prototype;
// 2 方法二:Student.prototype为Person的实例
// Student.prototype = new Person();
// 3 方法三:创建一个空对象,对象的原型指向Person.prototype,赋值给Student.prototype
Student.prototype = Object.create(Person.prototype);
Student.prototype.constructor = Student;
// 覆盖父类的info方法
Student.prototype.info = function () {
console.log('My name is ' + this.name + ',I\'m ' + this.age + ' years old now, and from class ' + this.className + '.');
};
// Student类的共享方法
Student.prototype.learn = function (subject) {
console.log(this.name + ' is learning ' + subject + '.');
};
// 测试,创建一个Student的实例
var zsqio = new Student('Zsqio', 21, 9);
zsqio.info(); // My name is Zsqio,I'm 21 years old now, and from class 9.
console.log(zsqio.LEGS_NUM); // 2
zsqio.walk(); // zsqio is walking...
zsqio.learn('JavaScript'); // zsqio is learning JavaScript.
console.log(zsqio.__proto__.__proto__ === Person.prototype); // true
console.log(zsqio.__proto__ === Student.prototype); // true
console.log(zsqio.__proto__.constructor === Student); // true