gpt4 book ai didi

javascript - 使用模块模式创建许多实例

转载 作者:行者123 更新时间:2023-12-03 00:05:05 25 4
gpt4 key购买 nike

我有两个文件:

let WordPair = function(wordA, wordB) {
function doSomething() { ... };

const smth = wordA + wordB;
return {doSomething, smth};
};
module.exports = WordPair;

-

let wordpair = require('./WordPair.js')('dog', 'cat');
wordpair.doSomething();

现在工作正常,但我想做的是创建 WordPair 的许多实例,例如像这样:

let arr = [];
for (let i = 0; i < 10; i++) {
arr.push(new WordPair('xyz', 'abc'));
}

换句话说:如何在 Java 中使用类的实例。在 Javascript 中实现此目的的正确方法是什么?

最佳答案

在 JavaScript 中,您可以使用原型(prototype)模式来实现

假设 doSomething 是结合了 wordA 和 wordB 的类方法

function WordPair(wordA, wordB){
this.wordA = wordA;
this.wordB = wordB;
}

WordPair.prototype.doSomething = function(){
const something = this.wordA + this.wordB;
console.log(something);
}

const wordPair = new WordPair('xyz', 'abc');

wordPair.doSomething();

或者更多es6类方式

class WordPair {

constructor(wordA, wordB){
this.wordA = wordA;
this.wordB = wordB;
}

doSomething(){
const something = this.wordA + this.wordB;
console.log(something);
}

}

const wordPair = new WordPair('xyz', 'abc');

wordPair.doSomething();

关于javascript - 使用模块模式创建许多实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54994674/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com