【问题标题】:Javascript function not getting called? Scope issue?Javascript函数没有被调用?范围问题?
【发布时间】:2020-01-19 18:08:14
【问题描述】:

我正在尝试对 json 对象执行验证。但似乎方法 ispoQuantityInvalid 方法根本没有被调用。

Fiddle

selectedRows = [{
    "itemNumber": "",
    "lineNumber": 1,
    "description": "PUMP,COMPLETE, P/N E12LYTFS-137",
    "uom": "",
    "poQuantity": "1",
    "recievedQuantity": "3",
    "isMatched": false,
    "p2PLineItemId": "168512",
    "quantityUnitPrice": "1",
    "buyerItemNumber": null
}];    


 ispoQuantityInvalid = () => (element, index, array) => {
 alert() //not getting called. 
    return this.isEmpty(element.poQuantity);
  }
console.log(this.selectedRows)

if (this.selectedRows.some(this.ispoQuantityInvalid)) {
     console.log('po qty is null or empty') //always gets called.
      return;
    }    

  isEmpty = (value) => {     
    return (value == null || value.length === 0 || value === '' || value == 0);
  }
  1. 即使poQuantity 不为空、不为空或不为0,它也未通过验证。
  2. 似乎ispoQuantityInvalid 方法根本没有被调用。我没有看到警报。

我在这里缺少什么? 这似乎是一个范围问题。但是我使用的箭头功能应该不会导致这个问题,对吧?

【问题讨论】:

  • () => (element, index, array) => {// do work} 语法无效。如果想要一个箭头函数而不传递任何东西,如果你想传递一个参数,你会使用() => {// do work},使用foo => {// do work}。如果需要传递多个,请使用(foo, bar) => {// do work}
  • @volt 谢谢,它正在调用该函数,但验证仍然失败this.isEmpty is not a function
  • ispoQuantityInvalid = … 正在创建一个全局变量,但 this.ispoQuantityInvalid 可能正在引用其他内容。确保正确设置变量的范围。
  • @volt It is valid,但你是对的,它没有做 OP 想要的

标签: javascript typescript validation ecmascript-6 scope


【解决方案1】:

改变

 ispoQuantityInvalid = () => (element, index, array) => {
 alert() //not getting called. 
    return this.isEmpty(element.poQuantity);
  }

 ispoQuantityInvalid = (element, index, arra) => {
 alert() //not getting called. 
    return this.isEmpty(element.poQuantity);
  }

第一个是返回要调用的函数的函数。因此内部函数仅可用但从未调用。然后 if 语句看起来像 if( function(e,i,a) {} ) 这不是假的,所以 if 语句体被执行。

【讨论】:

  • 该函数现在被调用,但它仍然失败。 this.isEmpty is not a function
  • 只需删除 isEmpty 之前的“this”。或者,如果您在对象上下文中并且需要 this(在我再次查看您的代码之后似乎就是这种情况),请将任何“this”绑定到您正在调用的函数中: if (this.selectedRows.some( this.ispoQuantityInvalid.bind(this)))
猜你喜欢
  • 1970-01-01
  • 2011-11-13
  • 1970-01-01
  • 2016-04-24
  • 1970-01-01
  • 2011-12-30
  • 2018-02-10
  • 2011-04-24
相关资源
最近更新 更多