这里说的继承是采用 call方法+原型改变指向来实现的。
继承在面向对象编程思想里面是非常重要的一块,能够减少代码的编写,方便后期维护,对于前端来说也是减少内存开辟的一个好的方式。不在这里过多的讨论面向对象的思想。先看看怎么实现。
代码:
function Person(name, age) {
this.name = name;
this.age = age;
this.run=function () {
console.log('run');
}
}
Person.prototype.eat = function () {
console.log(this.name+' eat')
}
function Student(name, age, school) {
Person.call(this,name, age)
this.school = school;
}
Student.prototype=new Person();
var s1 = new Student('cong', 26, "qust")
console.log(s1.name)
console.log(s1.age)
console.log(s1.school)
s1.eat();
运行结果:
现在详细讲讲为啥这么写;
其实 调用call行数和 原型重新指向都能实现继承,不过他们两个方法都有缺点。
比如单独使用call方法:
function Person(name, age) {
this.name = name;
this.age = age;
this.run=function () {
console.log(this.name+' run');
}
}
Person.prototype.eat = function () {
console.log(this.name+' eat')
}
function Student(name, age, school) {
Person.call(this,name, age)
this.school = school;
}
//Student.prototype=new Person();
var s1 = new Student('cong', 26, "qust")
console.log(s1.name)
console.log(s1.age)
console.log(s1.school)
s1.run();
s1.eat();
运行结果
会发现在实例中没有eat方法,我们输出一下s1对象看看结构
发现call方法只是将Person方法中的this变成了s1,之后将这些属性进行赋值了。而Person原型中的方法并没有在s1中体现。
那么单独使用原型重新指向那:
function Person(name, age) {
this.name = name;
this.age = age;
this.run=function () {
console.log(this.name+' run');
}
}
Person.prototype.eat = function () {
console.log(this.name+' eat')
}
function Student(name, age, school) {
// Person.call(this,name, age)
this.school = school;
}
Student.prototype=new Person();
var s1 = new Student('cong', 26, "qust")
console.log(s1.name)
console.log(s1.age)
console.log(s1.school)
s1.run();
s1.eat();
运行结果:
s1对象结果为
结果倒是有但是没有赋值。
如果这样赋值:Student.prototype=new Person(‘cong’,26);又不符合面向对象思想。
当然也可以之后一个一个属性进行赋值。
所以综上所述才用的组合的方式继承
-----------------------------分割线-----------------------
2021-11-08更新
也可以使用Object.call+Object.assign的方式来实现继承;
这样写的相比较原来的写法有个好处可以保留子类中prototype属性,并且可以实现多继承。
let Class1=function(){
this.fun1=function(){}
}
Class1.prototype.fun2=function(){}
let Class2=function(){
this.fun3=function(){}
Class1.call(this);
}
Class2.prototype.fun4=function(){}
Object.assign(Class2.prototype,Class1.prototype);
控制台输出