失败:无法读取属性'元素'未定义的

时间:2018-05-31 15:13:19

标签: javascript protractor

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

    class COMPLEYTYPENAMESerializer {
      static void serialize(IObjectName objectToSerialze, OutputByteStream outPutStream){
// some code will be here
         }

      static void dezerialize(IModifyNetModel modifyNetModel, InputByteStream  inputStream){
// some code will be here
                         }

    }

    class NetModelSerialize {
     sTATIC void serialize(IQueryNetModel,...) {
           // some code will be here

     } 
     static void dezerialize(IModifyNetModel modifyNetModel,...){
// some code will be here

}
    }

请帮我解决这个问题

  

失败:无法读取属性' SearchedClinic'未定义的。

正在显示。

能够执行到if语句。之后它会抛出错误作为上面的指定,并且执行立即停止

3 个答案:

答案 0 :(得分:2)

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

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

enter image description here

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

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

enter image description here

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

答案 1 :(得分:1)

您的function(rows)会创建一个新的关闭。这意味着该范围内的this不一定与外部的this相同。

有几种解决方案

  1. 在上面定义一个不同的变量,例如函数使用中的var self = this;

    self.SearchedClinic`
    
  2. 使用使用相同范围的ES6函数定义。

    this.SearchedClinic.count().then((count) => { 
    });
    
  3. 使用.bind(this)

    this.SearchedClinic.count().then((function (count) => { 
    }).bind(this));
    

答案 2 :(得分:0)

假设以下代码:

const result = obj1.printName.call(obj2);

在函数this下使用call将引用obj2,因为call()的第一个参数是显式设置this引用的内容。

这是您遇到的问题。

this.SearchedClinic.count().then(function(count){ 
    //calling this will reference the parameter count 
}

奖励之间的任何this都会引用该函数的第一个参数。 你要做的是声明一个全局变量:var searchedClinic = this.SearchedClinic。这是您的代码更新:

public SearchAndSelectClinicA(SearchName:string){
  var searchedClinic = this.SearchedClinic;
  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){
      searchedClinic.each(function(rows){ 
        rows.getText().then(function(value){
          if(value.indexOf(SearchName)){
            //Click the element if the statement is satisfied
            rows.click();
          }
        });
      });
    }
  });
}