javascript继承

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();

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值