繁体   English   中英

JavaScript 循环调用function时未定义

[英]JavaScript this is undefined when function called in a loop

我有以下代码,注释中解释了行为。 匿名 function 中undefined "this"的原因可能是什么?

 const getLength = (str) => { return str.length } const getDefaultValues = () => { const valueGetters = { A: { AA: { xpath: 'path', getValue: function () { return getLength(this.xpath) // <---- this is not undefined and returns value } }, AB: { xpath: 'path', getValue: function () { return getLength(this.xpath) // <---- this is not undefined and returns value } }, AC: { xpath: 'path', getValue: function () { return getLength(this.xpath) // <---- this is not undefined and returns value } }, AD: { xpath: 'path', getValue: function () { return getLength(this.xpath) // <---- this is not undefined and returns value } }, AE: { xpath: 'path', getValue: function () { return getLength(this.xpath) // <---- this is not undefined and returns value } }, GROSS: function () { // <--- when called in the loop, this returns 0 because all the ternary operators evaluate to false and return 0 // console.log('this', this) // <---- this is undefined const aa = this?.AA? this.AA.getValue(): 0 const ab = this?.AB? this.AB.getValue(): 0 const ac = this?.AC? this.AC.getValue(): 0 const ad = this?.AD? this.AD.getValue(): 0 const ae = this?.AE? this.AE.getValue(): 0 return aa + ab + ac + ad + ae } } } console.log('Calling without looping', valueGetters.A.GROSS()) // <--- This prints the correct value for gross without any problem // get the numerical values from the getters const valueEntries = Object.entries(valueGetters).map(([key, defaultValueGetter]) => { return [ key, Object.entries(defaultValueGetter).map( ([defaultValueKey, defaultValue]) => [ defaultValueKey, typeof defaultValue === 'function'? defaultValue(): defaultValue.getValue() // <--- I suspect that the problem is with this line ] ) ] }) return makeObject(valueEntries) } const makeObject = (arr) => { return Object.fromEntries( arr.map(([key, val]) => (Array.isArray(val)? [key, makeObject(val)]: [key, val])) ) } console.log(getDefaultValues())

您只是以defaultValue()形式调用 function,它不提供this上下文。 您需要明确提供this值,您可以使用.call()来完成。

typeof defaultValue === 'function' ? 
    defaultValue.call(defaultValueGetter) : 
    defaultValue.getValue()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM