JavaScript-如何将不同文件中的函数添加到类中?
我对OOP Javascript非常陌生,不确定如何完成以下任务: 我在我的index.js中有一个类,但由于我不想在索引文件中放一堆代码,我认为在不同的文件中分离会更有条理(比如在同一个文件中放在一起类似的函数) 每个函数依赖于两个常量,JavaScript-如何将不同文件中的函数添加到类中?,javascript,oop,Javascript,Oop,我对OOP Javascript非常陌生,不确定如何完成以下任务: 我在我的index.js中有一个类,但由于我不想在索引文件中放一堆代码,我认为在不同的文件中分离会更有条理(比如在同一个文件中放在一起类似的函数) 每个函数依赖于两个常量,key和secret,我在每个函数的内部使用这些参数。我可以通过以下方式轻松解决此问题: const Person function(key, secret) { this.functionOne = (key, secret, functionParam
key
和secret
,我在每个函数的内部使用这些参数。我可以通过以下方式轻松解决此问题:
const Person function(key, secret) {
this.functionOne = (key, secret, functionParameter) {};
}
但我不想每次使用functionOne
时都要求key
和secret
(它们是常量,就像api密钥和secret一样)。我想要的是,让每个函数(来自不同的文件)以某种方式从key
和secret
获取值,而不必在每次使用Person
的函数时手动输入。像这样:
index.js
const Person function(key, secret) {
this.personAction= (key, secret, thing) {};
}
personAction function(thing) {
// do something with key and secret
}
myFunctions.js
const Person function(key, secret) {
this.personAction= (key, secret, thing) {};
}
personAction function(thing) {
// do something with key and secret
}
然后才能做到这一点
const person1 = new Person('my_key123', 'my_secret123');
person.personAction('thing');
我能想到的唯一方法是将所有类似的函数放入它自己的类中,然后在我的主类(Person
)中,返回一个对象,用我的函数初始化每个类,如下所示:
// index.js
const Person function(key, secret) {
return {
myFunctions: new MyFunctions(key, secret),
otherFunctions: new OtherFunctions(key, secret)
}
}
// myFunctions.js
const MyFunctions function(key, secret) {
this.something= (thing) => {// do something with my key and secret}
}
通过这样做,我实际上可以做到:
const person1 = new Person('my_key', 'my_secret');
person1.myFunctions.something('hello')
但这感觉不是正确的方法,还有其他方法吗
p.S:如果我没有很好地解释我要做的事情,我很抱歉。如果我不够清楚,很难解释。请告诉我。不要用你自己的奇怪结构弯腰。这在标准OOP中得到了完美解决:
function Person(key, secret) {
this.key = key;
this.secret = secret;
}
Person.prototype.functionOne = function (functionParameter) {
console.log(this.key, this.secret, functionParameter);
};
var person1 = new Person('my_key', 'my_secret');
person1.functionOne('hello')
由于原型函数逐个附加到
prototype
属性,因此您可以轻松地将这些函数保存在不同的文件中,然后“将类放在一起”。但是,我不知道你为什么要这么做。通常,您希望在一个文件中保持一个类定义的自包含性,否则您将很难跟踪它的所有组件,并了解类的实际功能。唯一的例外是可以在不同类之间重用的“mixin”
const Person = function(key, secret) {
this.key = key;
this.secret = secret;
this.personAction= function(thing) {
//access this.key and this.secret
};
};
要将该方法放在单独的文件中,请尝试以下操作
const Person = function(key, secret) {
this.key = key;
this.secret = secret;
};
Person.prototype.personAction= function(thing) {
//access this.key and this.secret
};
第一个示例可以说根本不需要
这个
,您可以直接使用关闭的键
和秘密
。在OP的示例中,他正在做myFunctions:new myFunctions
,所以我想我们需要这个
。但是在这种情况下,key
和secret
都变为public@deceze我认为可能还有其他功能会溢出文件,因此添加了key
和secret
作为Person
的属性。