1.原型链
function Parent() {
};
// console.log(Parent.prototype.constructor);
// Parent.prototype.type = 'parent实例';
// Parent.prototype.sayType = function(){
// console.log(this.type);
// };
// 将Parent构造函数原型对象指向 Object实例对象 {}
// p1.constrctor--->Parent.prototype--->{}----->Object.prototype--->Object
Parent.prototype = {
constructor:Parent,
type: 'parent实例',
sayType: function () {
console.log(this.type);//c1.type
}
};
function Child() {};
// 将子构造函数原型对象指向父构造函数实例
Child.prototype = new Parent();
Child.prototype.constructor = Child;
var c1 = new Child();
console.log(c1.type);
c1.sayType();
parent.prototype={}(出了大问题了)把原型对象重新赋值,现在的原型对象等于花括号,花括号又是谁的实例,是object的实例。花括号当中只有我们的type属性,saytype:function,
parent.constructor由parent变成object是因为破坏原型链
2.经典继承
function Parent(name,age,gender){
// new关键字 this---->Parent实例
this.name = name;
this.age = age;
this.gender = gender;
this.sayAge = function(){
console.log(this.age)
}
}
// 提供子构造函数
function Child(name,age,gender,weight){
// Parent();//this---->Parent实例 为了指向子构造函数实例 修改this指向
// 经典继承 借用构造函数继承
Parent.call(this,name,age,gender);
this.weight = weight;
// this.name = name;//this---->Child实例
// this.age = age;
// this.gender = gender;
}
var c1 = new Child('terry',18,'male','40kg');
console.log(c1);
c1.sayAge();
3.组合继承
function Animal(type,age,weight,length){
this.type = type;
this.age = age;
this.weight = weight;
this.length = length;
}
// 提供父构造函数原型对象方法和属性
Animal.prototype = {
constructor:Animal,
atype:'父构造函数原型属性--atype',
sayType:function(){
console.log(this.type,'父构造函数原型对象方法')
}
}
// 子构造函数继承父构造函数 经典继承
function Dog(type,age,weight,length,name,color){
// 1.经典继承 借用构造函数继承
Animal.call(this,type,age,weight,length);
// this.type = type;
// this.age = age;
this.name = name;
this.color = color;
}
// 原型链继承 让子构造函数实例d1可以去继承父构造函数Animal属性和方法
// 将子构造函数原型对象指向父构造函数实例
Dog.prototype = new Animal();
Dog.prototype.constructor = Dog;
Dog.prototype.sayType = function(){
console.log('我是Dog原型方法');
}
var d1 = new Dog('狗',10,'20kg','40cm','可乐','白色');
// console.log(d1);
console.log(d1.type);
console.log(d1.atype);
d1.sayType();