this in Selenium’s get_eval() method

At Selenium Ruby site, there is a description for method get_eval(script), as following:

Gets the result of evaluating the specified JavaScript snippet. The snippet may have multiple lines, but only the result of the last line will be returned.

Note that, by default, the snippet will run in the context of the “selenium” object itself, so this will refer to the Selenium object. Use window to refer to the window of your application, e.g. window.document.getElementById(‘foo’) If you need to use a locator to refer to a single element in your application page, you can use this.browserbot.findElement("id=foo") where “id=foo” is your locator.

The special thing here is the this reference, means when invoking method get_eval() to run some javascript snippet, the this reference in snippet would refer to (redicted?) caller Selenium object but not the original belonging object.

This does differ from what we already know for window.eval() method, in which javascript snippt this still refer to the original belonging object, see below demo code:

var a = 0;
window.eval("this.a = 1"); // this refers to window object
alert(a); // a=1
alert(this.a == a) // true

Above code demos this is window object itself.

function A(){};
A.prototype = {
  f1: function(){
    return "f1";
  f2: function(){
var a = new A();
window.eval("a.f2()"); // equals to a.f2(), this in f2 refers to a.

Above code demos this in a.f2() method still refers to a, but not window object.

Generally, eval() is an evil thing.





One thought on “this in Selenium’s get_eval() method

  1. 其实this调用很简单。。。。就是单单指向对象本身罢。。。没你上面写的复杂。。。


您的电子邮箱地址不会被公开。 必填项已用*标注