10.继承方式一
2019-06-06 本文已影响0人
Fl_来看看
- Student.prototype.constructor = Student;修改了原型对象,记得构造函数也得修改回,因为如果仅仅是这样Student.prototype = new Person();,不加上加粗的语句,Student.prototype的值为Person构造函数的实例,而构造函数构造实例的过程中要new Object(设为A),且返回A。所以实质上,Student.prototype===A,而A.constructor ===Object,所以Student.prototype.constructor===Object,改变了,所以要Student.prototype.constructor===Student
Student.prototype = new Person();
Student.prototype.constructor = Student;
修改了原型对象,记得构造函数也得修改回
function Person() {
this.name = null;
this.age = 0;
this.say = function () {
console.log(this.name, this.age);
}
}
let per = new Person();
per.name = "lnj";
per.age = 34;
per.say();
// 在企业开发中如果构造函数和构造函数之间的关系是is a关系,
//那么就可以使用继承来优化代码, 来减少代码的冗余度
// 学生 is a 人 , 学生是一个人
//继承不能乱用,即使有共同的属性也不能用,
//比如狗有姓名,但狗不是人,得学生 is a 人 , 学生是一个人~!
function Student() {
this.score = 0;
this.study = function () {
console.log("day day up");
}
}
Student.prototype = new Person();
Student.prototype.constructor = Student;
let stu = new Student();
stu.name = "zs";
stu.age = 18;
stu.score = 99;
stu.say();
stu.study();
这种方式有弊端:无法在new Student();设置name,age,say。