我想通过Object.assign()
扩展对象:
extend.js
:
module.exports = {
get csrfOptions() {
return Object.assign({}, defaultOptions, this.securityOptions.csrf); //can't read property csrf of undefined
}
}
a.js
:
const extend = require('./extend.js');
const obj = {
securityOptions: {
csrf: {
name: 'laoqiren'
}
}
}
Object.assign(obj,extend);
出现错误can't read property csrf of undefined
,似乎在调用Object.assign()
的{{1}}函数的getter
时运行,但是csrfOptions
没有指向到this
中的obj
,这样就出现了错误。
然后,如何使用a.js
在obj
中扩展a.js
?
答案 0 :(得分:0)
Object.assign
复制属性值。您需要改为使用Object.defineProperties(obj, Object.getOwnPropertyDescriptors(extend))
“重新定义”属性。
这就是为什么在尝试获取csrfOptions
的值时会出错的原因。
const defaultOptions = {};
const extend = {
get csrfOptions() {
return Object.assign({}, defaultOptions, this.securityOptions.csrf); //can't read property csrf of undefined
}
}
const obj = {
securityOptions: {
csrf: {
name: 'laoqiren'
}
}
}
Object.defineProperties(obj, Object.getOwnPropertyDescriptors(extend))
console.log(obj.csrfOptions);