1、原型链来实现继承
原型链实现继承的本质是重新原型对象,代之以一个新类型的实例。
function Test(city) {
this.name = 'max';
this.city = city;
this.friends = ['egbert', 'helen', 'smith'];
}
Test.prototype.sayName = function() {
console.log('hi, my name is ' + this.name + '!');
}
function InhertTest() {
this.age = 24;
}
InhertTest.prototype = new Test();
var t = new InhertTest();
console.log(t.name); // 打印出来的是max
原型链继承有两个问题,一个是无法向超类型的构造函数传递参数,另一个是所有的InhertTest都会共享一个friends实例。friends存放在InhertTest.prototype中,所有实例都会共享。
2、借用构造函数
在子类型构造函数的内部调用超类型构造函数。
function Test(city) {
this.name = 'max';
this.city = city;
this.friends = ['egbert', 'helen', 'smith'];
}
Test.prototype.sayName = function() {
console.log('hi, my name is ' + this.name + '!');
}
function InhertTest(city) {
Test.call(this, city);
this.age = 24;
}
var t = new InhertTest('beijing');
console.log(t.city); // 打印出来的是beijing
PS: 为了保证超类型的属性不会覆盖子类型的属性,可以先调用超类型的构造函数。
这样写,name, city和friends都在InhertTest的实例上,也就是在t上。缺点就是子类型不能继承超类型在原型上的方法和属性。
PS:今天先写这两种吧,我要睡中觉了。。。