原型对象的继承
1:创建老师构造函数
function Teacher () {
this.name = "王老师";
this.age = 28;
this.sayHi = function () {
console.log("我是sayHi");
}
}
var teacher1 = new Teacher ();
2:创建学学生构造函数
function Student () {
this.name = "李雷";
this.age = 15;
this.sayHi = function () {
console.log("我是sayHi");
}
}
var stu1 = new Student ();
问题,怎么能让sayHi方法被老师学生都访问到?创建一个Person 构造函数
function Person () {
this.sayHi = function () {
console.log("我是sayHi");
}
}
先挂载到Person构造函数的原型对象上面
Person.prototype.sayHi = function () {
console.log("我是sayHi");
}
然后让Person构造函数的实例化对象覆盖其Student构造函数
Student.prototype = new Person();
网友评论