javascript - 失败 : Cannot read property 'element' of undefined

标签 javascript protractor

需要从arryelement中找出元素的个数,如果count>1则需要点击

/*search name is clinic name
clinicsearch is the arrayelement which has the list of clinic name list from the table*/
public SearchAndSelectClinicA(SearchName:string){
  this.ClinicSearch.sendKeys(SearchName);
  this.SearchIcon.click(); //click on the icon to get the clinic names
  this.SearchedClinic.count().then(function(count){
    //get the count of elements which are there in the Searchedclinic element array
    if(count>1){
      this.SearchedClinic.each(function(rows){ 
        /*Failed: Cannot read property 'SearchedClinic' of undefined 
          (Error gets displayed when it comes to above line.*/
        rows.getText().then(function(value){
          if(value.indexOf(SearchName)){
            //Click the element if the statement is satisfied
            rows.click();
          }
        });
      });
    }
  });
}

请帮我解决这个问题

Failed: Cannot read property 'SearchedClinic' of undefined.

正在显示。

它能够执行到if语句。稍后它会按照上面的说明抛出错误并立即停止执行

最佳答案

在 JavaScript 中,每个函数都有一个隐式的 this。在嵌套函数情况下使用 this 时需要小心。

下图说明了那些this来自哪个函数。

enter image description here

第二个 this.SearchedClinic 将尝试访问 this 属于嵌套函数:function(count){},它没有一个名为 SearchedClinic 的属性。

您希望 this 指向上面的那个。因此,您需要将顶部的 this 分配给另一个变量,如下所示:

enter image description here

现在 me 指向顶部的 this,您可以根据需要在任何嵌套函数中使用它。

关于javascript - 失败 : Cannot read property 'element' of undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50627570/

相关文章:

javascript - 检测 adblock 和 javascript

javascript - 在 jquery 中获取 datepicker 的值

angular - Protractor - 配置文件 'files' 中的 'tsconfig.json' 列表为空。 (18002)

javascript - 如何基于依赖于 specs jasmine 中其他函数的变量值运行函数?

javascript - Vue.js/Vuex : Calling getter vs Accessing state value directly on create lifecycle hook

javascript - 如何在 JavaScript 中使用 Math.random 进行测试?

javascript - Angular Protractor 在它上面循环 ('some test' ) 测试

javascript - Protractor js中的for循环

javascript - 从子表单组件传递和检索数据的最佳方法是什么?

selenium-webdriver - Protractor/Selenium Webdriver : Runtime. executionContextCreated 无效 'context'