新创建的对像属性值一样
创建如下所示的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();