javascript对象继承中的问题

新创建的对像属性值一样

创建如下所示的javascript对象,并执行代码:

    function Person(name ,age ,sex ,weight){
    	this.name = name;
    	this.age = age;
    	this.sex = sex;
    	this.weight = weight;
    }
    Person.prototype.sayHi(){
    	console.log('你好');
    }
    function Student(score){
    	this.score = score;
    }
    Student.prototype = new Person('小明',10,'男','50kg');
    var stu1 = new Student(100);
    console.log(stu1.name,stu1.age,stu1.sex,stu1.weight,stu1.score);
    var stu2 = new Student(200);
    console.log(stu2.name,stu2.age,stu2.sex,stu2.weight,stu2.score);
    var stu3 = new Student(300);
    console.log(stu3.name,stu3.age,stu3.sex,stu3.weight,stu3.score);

在这里插入图片描述
从执行结果,可以发现以下问题:
因为改变原型指向的同时实现继承,直接初始化了属性,继承过来的属性的值都是一样的了,所以这就是问题。
解决方法:

function Person(name ,age ,sex ,weight){
     this.name = name;
     this.age = age;
     this.sex = sex;
     this.weight = weight;
}
Person.prototype.sayHi(){
     console.log('你好');
}
function Student(name,age,sex,weight,score){
     //借用构造函数
     Person.call(this,name,age,sex,weight);
     this.score = score;
}
var stu1 = new Student('小明',20,'男','50kg',100);
console.log(stu1.name,stu1.age,stu1.sex,stu1.weight,stu1.score);
var stu2 = new Student('小红',21,'女','45kg',90);
console.log(stu2.name,stu2.age,stu2.sex,stu2.weight,stu2.score);
var stu3 = new Student('小李',23,'男','60kg',98);
console.log(stu3.name,stu3.age,stu3.sex,stu3.weight,stu3.score);

在这里插入图片描述

可以发现,对象的属性问题已经解决了,但是 person 对象的方法sayHi并没由继承过来。终极解决方案如(组合继承)下

function Person(name ,age ,sex ,weight){
     this.name = name;
     this.age = age;
     this.sex = sex;
     this.weight = weight;
}
Person.prototype.sayHi(){
     console.log('你好');
}
function Student(name,age,sex,weight,score){
     //借用构造函数
     Person.call(this,name,age,sex,weight);
     this.score = score;
}
Student.prototype = new Person();
var stu1 = new Student('小明',20,'男','50kg',100);
console.log(stu1.name,stu1.age,stu1.sex,stu1.weight,stu1.score);
stu1.sayHi();
var stu2 = new Student('小红',21,'女','45kg',90);
console.log(stu2.name,stu2.age,stu2.sex,stu2.weight,stu2.score);
stu2.sayHi();
var stu3 = new Student('小李',23,'男','60kg',98);
console.log(stu3.name,stu3.age,stu3.sex,stu3.weight,stu3.score);
stu3.sayHi();

在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值