JS中的继承(部分)

    科技2026-01-04  9

    JS中的继承(部分)

    什么是继承?

    继承可以在一个对象中去访问另一个对象的方法或者属性,提高代码自由度。

    方法

    一、通过call继承

    1.解决引用类型继承问题 例:

    // 父类 function Parent(name) { this.name = name; this.color = ['pink', 'red']; } // 子类 function Child() { Parent.call(this); // 定义自己的属性 this.value = 'test'; } var child1 = new Child(); var child2 = new Child(); // 先输出child1和child2种color的值 console.log(child1.color); // ["pink", "red"] console.log(child2.color); // ["pink", "red"] // 在child1的color数组添加white child1.color.push('white'); console.log(child1.color); // ["pink", "red", "white"] // child1上的改动,child2并没有受到影响 console.log(child2.color); // ["pink", "red"]

    2.解决传参数问题 例:

    // 父类 function Parent(name) { this.name = name; this.color = ['pink', 'red']; } // 子类 function Child(name) { Parent.call(this, name); // 定义自己的属性 this.value = 'test'; } var child = new Child('小明'); // 将'小明'传递给Parent console.log(child.name); // 小明

    在这里,我们借用call函数可以改变函数作用域的特性,在子类中调用父类构造函数,复制父类的属性。此时没调用一次子类,复制一次。此时,每个实例都有自己的属性,不共享。同时我们可以通过call函数给父类传递参数。 弊端:共享的方法都在构造函数中定义,无法达到函数复用的效果。

    二、通过原型链继承

    例:

    // 父类 function Parent() { this.value = 'value'; } Parent.prototype.sayHi = function() { console.log('Hi'); } // 子类 function Child() { // 改变子类的prototype属性为父类的实例 Child.prototype = new Parent(); var child = new Child(); // 首先现在child实例上进行查找,未找到, // 然后找到原型对象(Parent类的一个实例),在进行查找,未找到, // 在根据__proto__进行找到原型,发现sayHi方法。 // 实现了Child继承 child.sayHi();

    弊端:实例化子类的时候,无法给父类传参。

    Processed: 0.049, SQL: 9