我试图创建一个对象,并想通过调用其他字段来设置某些字段。我收到错误
base: `${this.api.foo.domain}${this.api.foo.port}${this.api.foo.version}`,
^
TypeError: Cannot read property 'foo' of undefined
代码:
module.exports = {
api: {
foo: {
domain: 'api.foo.com',
port: ':8080',
version: '/v1',
base: `${this.api.foo.domain}${this.api.foo.port}${this.api.foo.version}`,
verifyToken: `${this.api.foo.base}/oauth/token/{bearerToken}`,
}
}
};
如何正确调用字段?
答案 0 :(得分:0)
this
不是引用该对象,而是引用上下文,在这种情况下,该上下文未定义(因为代码是全局的,并且不在方法内部)。为了能够引用对象的值,必须将属性移到对象之外,并在声明对象后将其附加:
const data = {
api: {
foo: {
domain: 'api.foo.com',
port: ':8080',
version: '/v1',
}
}
};
data.api.foo.base = `${data.api.foo.domain}${data.api.foo.port}${data.api.foo.version}`;
data.api.foo.verifyToken = `${data.api.foo.base}/oauth/token/{bearerToken}`;
module.exports = data;