学习了ES5中类的继承相关视频,记录一下,先看看准备工作
// 第一类人
function PersonTypeOne() {
this.name = "王陆";
this.age = "22";
this.run = function () {
console.log(this.name + "在奔跑");
}
}
// 添加第一类人原型链方法
PersonTypeOne.prototype.work = function () {
console.log(this.name + "在工作");
}
// 第二类人
function PersonTypeTwo(name, age) {
this.name = name;
this.age = age;
this.run = function () {
console.log(this.name + "在奔跑");
}
}
// 添加第二类人原型链方法
PersonTypeTwo.prototype.work = function () {
console.log(this.name + "在工作");
}
// 实例化第一类人
var p1 = new PersonTypeOne();
// 执行方法
p1.run();
p1.work();
// 实例化第二类人
var p2 = new PersonTypeTwo("王舞", 22);
p2.run();
p2.work();
第一类人不需要实例化时不需要传递参数,第二类人实例化时需要传递参数,主要也是为了对比,至于写的原型链方法也是为了看冒充对象继承和原型链继承的区别以及特点。
先看看冒充对象的继承
// 冒充对象的继承
function test1() {
PersonTypeOne.call(this);
}
var t1 = new test1();
t1.run();
t1.work();
从提示来看,原型链方法work并没有继承过来,那使用另一种继承方法看看
原型链继承
// 原型链继承
function test2() {}
test2.prototype = new PersonTypeOne;
var t2 = new test2();
t2.run();
t2.work();
这一次类中的方法和原型链方法都继承多来了,但是这种继承存在问题,这次继承实例需要传参的第二类人。
function test21() {}
test21.prototype = new PersonTypeTwo;
var t21 = new test21("小明",21);
t21.run();
t21.work();
从结果分析可知参数并没有传过去,那么想要传参,需要怎么做呢
冒充对象+原型链继承
function test22(name, age) {
PersonTypeTwo.call(this, name, age);
}
test22.prototype = PersonTypeTwo.prototype;
var test22 = new test22("小明", 22);
test22.run();
test22.work();
搞定