[英]Javascript: how can I access a class property to a function inside nested object
I'm working with javascript classes and there's something I want to do but I don't know how. 我正在使用javascript类,我想做但我不知道如何做。 First of all, this is my class:
首先,这是我的班级:
class Company {
constructor (options) {
this.employee = options.employee;
this.algorithm = "AZ1";
}
}
Now, employee is an object which has another object nested inside of it and that final object contains a series of functions: 现在,employee是一个对象,它有另一个嵌套在其中的对象,最终对象包含一系列函数:
employee {
code {
generate [Function: generate]
alter [Function: alter]
}
}
Now, my problem is that I want to access the algorithm
from any of these functions? 现在,我的问题是我想从这些函数中的任何一个访问
algorithm
?
Btw; 顺便说一句, I'm trying to do so from an object created with that class:
我正在尝试从使用该类创建的对象执行此操作:
const myCompany = new Company({ employee });
So I want to access the algorithm
property from the generate function within myCompany
. 所以我想从
myCompany
的generate函数访问algorithm
属性。
You should be able to access the algorithm like this: myCompany.employee.code.generate(myCompany.algorithm)
你应该能够像这样访问算法:
myCompany.employee.code.generate(myCompany.algorithm)
EDIT: It wasn't clear from your original question that you're trying to keep the algorithm private to the class. 编辑:从您的原始问题中不清楚您是否试图将算法保持为类私有。 Something like this might work:
像这样的东西可能会起作用:
class Company {
constructor (options) {
this.employee = options.employee;
this.algorithm = "AZ1";
}
generateEmployee = () => {
this.employee.code.generate(this.algorithm);
}
}
This would give you a myCompany.generateEmployee
method that the caller could use without passing in the algorithm. 这将为您提供一个
myCompany.generateEmployee
方法,调用者可以在不传递算法的情况下使用该方法。
Note that this syntax will only work if you're using a transpiler like Babel. 请注意,只有在使用像Babel这样的转换器时,此语法才有效。 If not, you can use this syntax (so your method has the right
this
context): 如果没有,您可以使用此语法(因此您的方法具有正确的
this
上下文):
class Company {
constructor (options) {
this.employee = options.employee;
this.algorithm = "AZ1";
this.generateEmployee = this.generateEmployee.bind(this);
}
generateEmployee() {
this.employee.code.generate(this.algorithm);
}
}
object1.field1 = object2
is a one-way relation: object1.field1 = object2
是单向关系:
object1
can access object2
afterwards, via field1
object1
可以通过field1
访问object2
object2
has absolutely no clue about object1
being around, and thus it can not know about its other fields either. object2
完全没有关于object1
在周围的线索,因此它也无法知道其他字段。 You can pass it as an argument, like object1.field1.dosomething(object1.field2)
, which in the actual case translates to: 您可以将其作为参数传递,例如
object1.field1.dosomething(object1.field2)
,在实际情况下转换为:
myCompany.employee.code.generate(myCompany.algorithm)
(And of course assumes that generate()
is modified to expect such argument. The freshly added option
does not affect the pattern) (当然假设
generate()
被修改为期望这样的参数。新添加的option
不会影响模式)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.