首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

在JavaScript中调用父“类”上的函数

在JavaScript中调用父类上的函数可以通过使用super关键字来实现。super关键字用于调用父类的构造函数、静态方法和原型方法。

在ES6之前,可以使用Object.getPrototypeOf(this)来获取当前对象的原型,然后通过原型链找到父类的原型,再调用父类的方法。示例代码如下:

代码语言:txt
复制
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关键字直接调用父类的方法。示例代码如下:

代码语言:txt
复制
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()调用了父类ParentsayHello方法。

在腾讯云的产品中,与JavaScript开发相关的产品有云函数(Serverless Cloud Function)和云开发(Tencent CloudBase)。云函数是一种无需管理服务器即可运行代码的计算服务,可以用于编写和运行JavaScript函数。云开发是一套面向开发者的全栈云开发平台,提供了云函数、数据库、存储等功能,支持JavaScript开发。相关产品介绍链接如下:

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

领券