首页 > 解决方案 > 从构造函数调用 JS 原型函数(ES6 模块)

问题描述

我正在重写一些作为ES6模块的JavaScript脚本代码,并且在调用原型函数时遇到问题。

原始脚本的结构是这样的:

function randomThing(a) {
    this.a = a
    this.doRandomThing()
    ..
}

randomThing.prototype.doRandomThing = function () { ... }

但是,调用与此。不再在模块中工作。

export default function randomThing(a) {
    this.a = a
    this.doRandomThing() // error: this.doRandomThing is not a function
    ..
}

randomThing.prototype.doRandomThing = function () { ... }

如何从构造函数中调用doRandomThing()函数?我想我可以在构造函数中将它定义为 var,但是有没有办法使用.prototype语法来保持版本?

标签: javascriptecmascript-6

解决方案


推荐阅读