在JavaScript中调用父类上的函数可以通过使用super
关键字来实现。super
关键字用于调用父类的构造函数、静态方法和原型方法。
在ES6之前,可以使用Object.getPrototypeOf(this)
来获取当前对象的原型,然后通过原型链找到父类的原型,再调用父类的方法。示例代码如下:
function Parent() {
this.name = 'Parent';
}
Parent.prototype.sayHello = function() {
console.log('Hello from Parent');
}
function Child() {
Parent.call(this);
this.name = 'Child';
}
Child.prototype = Object.create(Parent.prototype);
Child.prototype.constructor = Child;
Child.prototype.sayHello = function() {
// 调用父类的sayHello方法
Parent.prototype.sayHello.call(this);
console.log('Hello from Child');
}
var child = new Child();
child.sayHello();
在ES6中,可以使用super
关键字直接调用父类的方法。示例代码如下:
class Parent {
constructor() {
this.name = 'Parent';
}
sayHello() {
console.log('Hello from Parent');
}
}
class Child extends Parent {
constructor() {
super();
this.name = 'Child';
}
sayHello() {
// 调用父类的sayHello方法
super.sayHello();
console.log('Hello from Child');
}
}
var child = new Child();
child.sayHello();
以上代码中,super.sayHello()
调用了父类Parent
的sayHello
方法。
在腾讯云的产品中,与JavaScript开发相关的产品有云函数(Serverless Cloud Function)和云开发(Tencent CloudBase)。云函数是一种无需管理服务器即可运行代码的计算服务,可以用于编写和运行JavaScript函数。云开发是一套面向开发者的全栈云开发平台,提供了云函数、数据库、存储等功能,支持JavaScript开发。相关产品介绍链接如下:
领取专属 10元无门槛券
手把手带您无忧上云