原型继承、构造函数继承、组合继承法

原型继承


function Person(name,sex){
    this.name=name;
    this.sex=sex;
    this.friends = {lily:'female',lucy:'female'};
    this.showFriends=function(){
        var str = ''
        for(i in this.friends){
            str+=i +' '+this.friends[i] +',';
        }
        console.log('my friends:'+str);
    }
}
Person.prototype.hello=function(){
    console.log('hello:'+this.name);
}

var per1 =  new Person('A','male');
per1.hello();
per1.showFriends();


function Student(className){
    this.class = className;
}

Student.prototype = new Person('B','male');//原型继承将子对象的原型对象指向父对象的实例 ; 缺点:不能由子对象像父对象传递参数,

var stu1 = new Student(1);//不能由子对象像父对象传递参数,
stu1.name='C';
stu1.hello();
stu1.friends.C = 'male';//2、对于引用型的属性修改之后会印象其他的实例对象;
stu1.showFriends();//2、对于引用型的属性修改之后会印象其他的实例对象;

console.log("stu1 instanceof Student: ");
console.log(stu1 instanceof Student);
console.log("stu1 instanceof Person: ");
console.log(stu1 instanceof Person);

var stu2 = new Student(2);
stu2.name='D';
stu2.hello();
stu2.showFriends();//2、对于引用型的属性修改之后会印象其他的实例对象;

console.log("stu2 instanceof Student: ");
console.log(stu2 instanceof Student);
console.log("stu2 instanceof Person: ");
console.log(stu2 instanceof Person);

clipboard.png

缺点:1、不能由子对象像父对象传递参数,2、对于引用型的属性修改之后会印象其他的实例对象;

构造函数继承

//构造函数继承
function Teacher(name,sex,type){
    this.type=type;
    Person.call(this,name,sex);
}

var tea1 = new Teacher('E','female','数学');
//tea1.hello(); //报错没有继承到原型上的方法
tea1.friends.F = 'male';
tea1.showFriends();

var tea2 = new Teacher('G','male','语文');
tea2.friends.H = 'male';
tea2.showFriends();
console.log("tea2 instanceof Teacher: ")
console.log(tea2 instanceof Teacher);
console.log("tea2 instanceof Person: ")
console.log(tea2 instanceof Person);

clipboard.png

缺点:1、不能继承父对象原型上的方法 2、每次实例化对象会重新构建函数,浪费内存。

组合继承法

把父对象方法挂载到父类的原型对象上去,实现方法复用
function Worker(name,sex,job){
    this.job = job;
    Person.call(this,name,sex)
}
Worker.prototype = new Person();
Worker.prototype.constructor = Worker;//原型的构造函数指向worker

var wor1 = new Worker('I','female','程序员');
wor1.hello();
wor1.friends.J = 'male';
wor1.showFriends();

clipboard.png

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值