JavaScript中的继承可以通过原型链来实现。在原型链中,子类的原型对象是父类的一个实例,因此子类可以继承父类的属性和方法。
function Parent(name) {
this.name = name;
}
Parent.prototype.sayHello = function() {
console.log(`Hello, my name is ${this.name}`);
}
function Child(name, age) {
Parent.call(this, name);
this.age = age;
}
Child.prototype = Object.create(Parent.prototype);
Child.prototype.constructor = Child;
在上面的例子中,我们定义了一个父类Parent和一个子类Child。在子类的构造函数中,我们调用了父类的构造函数,并传递了必要的参数。然后,我们使用Object.create()方法将子类的原型对象设置为父类的实例,以实现继承。最后,我们将子类的构造函数设置为Child。
在JavaScript中,每个对象都有一个原型对象。原型对象是一个普通的对象,它包含了一些可共享的属性和方法。当我们访问一个对象的属性或方法时,如果该对象本身没有该属性或方法,JavaScript引擎会沿着原型链向上查找,直到找到该属性或方法为止。
function Person(name) {
this.name = name;
}
Person.prototype.sayHello = function() {
console.log(`Hello, my name is ${this.name}`);
}
function Student(name, grade) {
Person.call(this, name);
this.grade = grade;
}
Student.prototype = Object.create(Person.prototype);
Student.prototype.constructor = Student;
const john = new Student("John", 10);
john.sayHello();
在上面的代码中,我们定义了一个Person类和一个Student类。Student类继承自Person类。当我们创建一个Student对象时,它会继承Person对象的原型链。因此,我们可以在Student对象中调用Person对象的方法。