1.借用构造函数
function Person(name, age){
this.name = name;
this.age = age;
}
Person.prototype.getName = function(){
return this.name;
};
function Worker(){
Person.apply(this,arguments);
this.job = function(){
console.log('worker');
}
}
var worker = new Worker('hqq',22);
console.log(worker);//不能继承原型链中的getName
缺点方法无法复用,而且Person原型中定义的方法在Student中也是不可见的,so 这种方法很少单独使用,
还有new运算符会让构造器函数里的this指向本身,普通函数中的this一般指向window(处闭包等)。
2.组合继承
上面代码的改善版:
将原型链(方法复用)和借用构造函数(封装属性)组合,成为最常用的继承方式。
function Person(name){
this.name = name;
}
Person.prototype.sayName = function(){
return this.name;
}
function Student(name){
Person.call(this,name);
}
Student.prototype = new Person();如果去掉这句就会报错sayName()方法没找到。
var p = new Student('hqq');
console.log(p.name);
console.log(p.sayName());
3.原型式继承
Object.create()方法就是这样的思想(此对象的原型指向括号内的对象),只是它多了一个参数。
function Obj(o){
function func(){}
func.prototype = o;
return new func();
}
var person = {
name : 'qq',
friends : ['1','2']
}
var p = new Obj(person);//p的原型指向Person
p.friends.push('3');
console.log(p.friends);//['1','2','3']
4.寄生式继承
function Obj(o){
function func(){}
func.prototype = o;
return new func();
}
function createObject(o){
var p = Obj(o);
p.getName = function(){
return this.name;
}
return p;
}
var person = {
name : 'qq',
friends : ['1','2']
}
var p = new createObject(person);//p的原型指向Person
console.log(p.getName());
OK,把书上的每个例题都思考着过一遍,然后有一天我就成为大神了,嘿嘿~~~~~~加油!