扩展Javascript中的对象

时间:2018-07-13 09:15:11

标签: 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
    }
}

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.jsobj中扩展a.js

1 个答案:

答案 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);