1.原型链继承 每个构造函数都有一个原型对象,原型对象中都包含一个指向构造函数的指针,而实例都包含一个指向原型对象的内部指针。当原型对象等于另外一个类型的实例即继承。调用某个方法或者属性的步骤 1.搜索实例 2.搜索原型 3.搜索父构造函数原型 //定义父类类型 function Animal(){ this.name = “animal” } Animal.prototype = { sayName : function(){ alert(this.name); } }
function Animal () {
this.name = "animal";
}
Animal.prototype.sayName = function () {
console.log(this.name);
}
function Dog () {
this.color = "black";
}
Dog.prototype = new Animal();
Dog.prototype.sayColor = function () {
console.log(this.color);
}
var dog = new Dog();
console.log(dog);
dog.sayName();
dog.sayColor();
结果:
Animal { color: 'black' }
animal
black
2.经典继承(也叫借用构造函数、也叫伪造对象):不仅可以继承方法,也可以继承属性
本质上不算是继承,只能算是方法的调用
function Animal(name,age){
this.name = name;
this.age = age;
this.sayName=function(){
console.log(this.name);
}
}
Animal.prototype.sayAge = function(){
console.log(this.age);
}
function Dog(name,age,color,type){
Animal.call(this,name,age);
this.color = color;
this.type = type;
}
var dog = new Dog("一休",1,"yellow","金毛");
console.log(dog);
dog.sayName();
dog.sayAge();
结果:
Dog {
name: '一休',
age: 1,
sayName: [Function (anonymous)],
color: 'yellow',
type: '金毛'
}
一休
3.组合继承(也称"伪经典继承"): 将原型链和借用构造函数的技术组合在一起。 原型链继承+经典继承 继承属性和方法,以及原型中的属性和方法 原理是:使用原型链实现对原型属性和方法的继承,而通过借用构造函数实现对实例属性的继承。 // 原型链继承是说让子对象的原型指向父对象的实例
function Animal(name,age){
this.name = name;
this.age = age;
}
Animal.prototype = {
constructor:Animal,
sayHello:function(){
console.log(this.name+"say hello");
}
};
function Dog(name,age,color){
Animal.call(this,name,age);
this.color = color;
}
Dog.prototype = new Animal();
Dog.prototype.constructor = Dog;
Dog.prototype.sayColor = function(){
console.log(this.color);
}
var dog = new Dog("一休",1,"yellow");
console.log(dog);
dog.sayHello();
dog.sayColor();
console.log(dog.__proto__);
console.log(dog.__proto__.__proto__);
console.log(Animal.prototype);
结果:
Dog { name: '一休', age: 1, color: 'yellow' }
一休say hello
yellow
Animal {
name: undefined,
age: undefined,
constructor: [Function: Dog],
sayColor: [Function (anonymous)]
}
{ constructor: [Function: Animal], sayHello: [Function: sayHello] }
{ constructor: [Function: Animal], sayHello: [Function: sayHello] }
|