javascript 的继承
在JavaScript中实现继承是Web开发者们经常遇到的问题之一。因为在JavaScript中,没有 Class 这个概念,因此要实现继承需要使用一些特殊的技巧。
比如说,当我们想要创建一个新的对象并且让其具备一些父类对象的属性和方法时,我们可以通过prototype属性来实现继承。
function Person(name, age) {this.name = name;this.age = age;}Person.prototype.sayHello = function() {console.log('Hello, my name is ' + this.name);}function Student(name, age, grade) {this.grade = grade;Person.call(this, name, age);}Student.prototype = Object.create(Person.prototype);Student.prototype.constructor = Student;Student.prototype.sayGrade = function() {console.log('I am in grade ' + this.grade);}var alice = new Student('Alice', 16, 11);alice.sayHello(); // 'Hello, my name is Alice'alice.sayGrade(); // 'I am in grade 11'这里,我们定义了一个Person构造函数来创建一个 Person 对象,它具有name和age属性以及一个sayHello方法。接着我们定义了一个Student构造函数来创建一个 Student 对象,它继承自 Person,并且具有一个grade属性以及一个sayGrade方法。
关键的部分是这行代码:
Student.prototype = Object.create(Person.prototype);
这行代码通过创建一个新对象,并将该对象的原型设置为 Person 的原型,从而实现了 Student 继承自 Person。接着,我们还需要重置 Student 构造函数的指向:
Student.prototype.constructor = Student;
这便是我们实现继承的基本思路。当使用new关键字创建一个 Student 对象时,我们在 Student 构造函数中调用了 Person,并通过call函数将新创建的 Student 对象作为 this 传递给它。于是,我们便可以在新创建的对象上添加新的属性和方法及其继承的属性和方法。
JavaScript的继承还可以使用 ES6 中的 class 语法来实现:
class Person {constructor(name, age) {this.name = name;this.age = age;}sayHello() {console.log('Hello, my name is ' + this.name);}}class Student extends Person {constructor(name, age, grade) {super(name, age);this.grade = grade;}sayGrade() {console.log('I am in grade ' + this.grade);}}let alice = new Student('Alice', 16, 11);alice.sayHello(); // 'Hello, my name is Alice'alice.sayGrade(); // 'I am in grade 11'可以看到,class 中的 extends 关键字使得 Student 继承自 Person,而不需要手动设置 Student 的原型。
JavaScript 的继承虽然看起来有些奇怪,但是它的灵活性和可扩展性使得它成为了一个非常好用的编程语言。掌握了 JavaScript 的继承,对于 Web 开发者们来说是一个非常重要的能力。
免责声明:本文内容来自用户上传并发布,站点仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。请核实广告和内容真实性,谨慎使用。