rubyjs / therubyrhino

Embed the Mozilla Rhino Javascript interpreter into Ruby
155 stars 40 forks source link

`this` is weird when you use `#call` #39

Open judofyr opened 6 years ago

judofyr commented 6 years ago
require 'rhino'
p Rhino::VERSION  # => 2.0.4

ctx = Rhino::Context.new
ctx.eval('this.bar = 123');
p ctx.eval('(function() { return this.bar })()')     # => 123 (as expected)
p ctx.eval('this.bar')                               # => 123 (as expected)
p ctx.eval('(function() { return this.bar })').call  # => nil ???

Seems like there a different this when you invoke a function through #call.

kares commented 6 years ago

believe this is proper JS -> in the last case this is the global object :)

judofyr commented 6 years ago

Why isn't this the global object in all of the examples? If I bind to null and call the function I get 123. There seems to be two different global objects in play here?

require 'rhino'
p Rhino::VERSION  # => 2.0.4

ctx = Rhino::Context.new
ctx.eval('this.bar = 123');
p ctx.eval('(function() { return this.bar })()')     # => 123 (as expected)
p ctx.eval('this.bar')                               # => 123 (as expected)
p ctx.eval('(function() { return this.bar })').call  # => nil ???
p ctx.eval('(function() { return this.bar }).bind(null).call()') # => 123 (as expected)