Javascript中的扩展对象
我想通过Javascript中的扩展对象,javascript,typescript,oop,Javascript,Typescript,Oop,我想通过object.assign()扩展对象: extend.js: module.exports = { get csrfOptions() { return Object.assign({}, defaultOptions, this.securityOptions.csrf); //can't read property csrf of undefined } } const extend = require('./extend.js'); const o
object.assign()
扩展对象:
extend.js
:
module.exports = {
get csrfOptions() {
return Object.assign({}, defaultOptions, this.securityOptions.csrf); //can't read property csrf of undefined
}
}
const extend = require('./extend.js');
const obj = {
securityOptions: {
csrf: {
name: 'laoqiren'
}
}
}
Object.assign(obj,extend);
a.js
:
module.exports = {
get csrfOptions() {
return Object.assign({}, defaultOptions, this.securityOptions.csrf); //can't read property csrf of undefined
}
}
const extend = require('./extend.js');
const obj = {
securityOptions: {
csrf: {
name: 'laoqiren'
}
}
}
Object.assign(obj,extend);
错误是,无法读取未定义的属性csrf
,调用Object.assign()
时,csrfOptions
函数的getter
运行,但此没有指向a.js
中的obj
,因此错误出现
然后,如何使用extend.js
对象在a.js
中扩展obj
?对象。分配
复制属性值。您需要使用Object.defineProperties(obj,Object.getOwnPropertyDescriptors(extend))
来“重新定义”属性
这就是为什么在尝试获取csrfOptions
的值时会出现错误
constdefaultoptions={};
常数扩展={
获取csrfOptions(){
return Object.assign({},defaultOptions,this.securityOptions.csrf);//无法读取未定义的属性csrf
}
}
常量对象={
安全选项:{
csrf:{
姓名:“老七人”
}
}
}
Object.defineProperties(obj,Object.getOwnPropertyDescriptors(扩展))
console.log(obj.csrfOptions)
看起来像typescript,但您从未提及它,也没有它的标记。您还拼错了require
。我认为module.exports部分包含几个错误。首先,fn名称和CSRFOptions中的空白?小提示extend
每当传递函数时,此
未定义,。。这是我们进来的时候。。IOW:您可以尝试Object.assign(obj,extend.bind(obj)
@Keith对象没有bind
方法哦,是的..读错了..您如何调用csrfOptions
?