返回
JavaScript 继承大揭秘:初级前端面试必杀技!
前端
2023-10-26 05:16:03
在 JavaScript 中,继承是指创建子类型,使其可以访问和继承父类型中的属性和行为。这种代码复用和分离设计的能力,是现代软件开发中的基石。
在 ES5 中,可以使用原型链继承来实现继承。顾名思义,原型链是一种链接对象原型对象的链式结构。子类型通过其原型对象指向父类型的原型对象,从而获得父类型的属性和方法。
而 ES6 引入了 class ,提供了一种更简洁、更易于理解的方式来实现继承。ES6 中的 class 继承基于构造函数继承,它直接将父类的构造函数作为子类的构造函数的原型。
为了进一步理解 ES5 和 ES6 中的继承,我们举一个简单的例子:
ES5 原型链继承:
function Person(name) {
this.name = name;
}
Person.prototype.getName = function() {
return this.name;
};
function Employee(name, salary) {
// 通过原型链继承
Person.call(this, name);
this.salary = salary;
}
Employee.prototype = Object.create(Person.prototype);
Employee.prototype.getSalary = function() {
return this.salary;
};
ES6 class 继承:
class Person {
constructor(name) {
this.name = name;
}
getName() {
return this.name;
}
}
class Employee extends Person {
constructor(name, salary) {
super(name);
this.salary = salary;
}
getSalary() {
return this.salary;
}
}
在这些示例中,Employee 类继承了 Person 类,拥有了 name 属性和 getName 方法,同时还增加了 salary 属性和 getSalary 方法。
掌握 JavaScript 继承对于前端开发人员至关重要,它可以让你的代码更加模块化、可扩展和易于维护。无论是初级前端面试还是实际项目开发,本文提供的指南都会助你成为 JavaScript 继承的专家。