mirror of
https://github.com/rubyjs/therubyrhino
synced 2023-03-27 23:21:34 -04:00
#apply seems as a better name for #methodcall + add some notes on #call semantics in JS vs. Ruby
This commit is contained in:
parent
176bf1ffe9
commit
28a9322a3e
2 changed files with 27 additions and 3 deletions
|
@ -150,6 +150,10 @@ class Java::OrgMozillaJavascript::BaseFunction
|
|||
alias_method :__call__, :call
|
||||
|
||||
# make JavaScript functions callable Ruby style e.g. `fn.call('42')`
|
||||
#
|
||||
# NOTE: That invoking #call does not have the same semantics as
|
||||
# JavaScript's Function#call but rather as Ruby's Method#call !
|
||||
# Use #apply or #bind before calling to achieve the same effect.
|
||||
def call(*args)
|
||||
context = Rhino::JS::Context.enter; scope = current_scope(context)
|
||||
# calling as a (var) stored function - no this === undefined "use strict"
|
||||
|
@ -160,6 +164,7 @@ class Java::OrgMozillaJavascript::BaseFunction
|
|||
Rhino::JS::Context.exit
|
||||
end
|
||||
|
||||
# bind a JavaScript function into the given (this) context
|
||||
def bind(this, *args)
|
||||
context = Rhino::JS::Context.enter; scope = current_scope(context)
|
||||
args = Rhino.args_to_javascript(args, scope)
|
||||
|
@ -176,13 +181,19 @@ class Java::OrgMozillaJavascript::BaseFunction
|
|||
Rhino::JS::Context.exit
|
||||
end
|
||||
|
||||
def methodcall(this, *args)
|
||||
# apply a function with the given context and (optional) arguments
|
||||
# e.g. `fn.apply(obj, 1, 2)`
|
||||
#
|
||||
# NOTE: That #call from Ruby does not have the same semantics as
|
||||
# JavaScript's Function#call but rather as Ruby's Method#call !
|
||||
def apply(this, *args)
|
||||
context = Rhino::JS::Context.enter; scope = current_scope(context)
|
||||
args = Rhino.args_to_javascript(args, scope)
|
||||
__call__(context, scope, Rhino.to_javascript(this), args)
|
||||
ensure
|
||||
Rhino::JS::Context.exit
|
||||
end
|
||||
alias_method :methodcall, :apply # V8::Function compatibility
|
||||
|
||||
end
|
||||
|
||||
|
|
|
@ -166,9 +166,22 @@ describe "NativeFunction" do
|
|||
5.times { |i| this.get(i, this).should == i }
|
||||
end
|
||||
|
||||
it 'might be method-called' do
|
||||
it 'might be applied' do
|
||||
an_obj = @context.newObject(@scope)
|
||||
@object.methodcall(an_obj).should == '[object Object]'
|
||||
@object.apply(an_obj).should == '[object Object]'
|
||||
|
||||
array = @context.newArray(@scope, [].to_java)
|
||||
push = Rhino::JS::ScriptableObject.getProperty(array, 'splice')
|
||||
|
||||
this = @context.newArray(@scope, [ 0, 3, 4 ].to_java)
|
||||
push.apply(this, 1, 0, 1, 2)
|
||||
|
||||
this.length.should == 5
|
||||
5.times { |i| this.get(i, this).should == i }
|
||||
end
|
||||
|
||||
it 'might get method-called' do
|
||||
@object.method(:apply).should == @object.method(:methodcall)
|
||||
end
|
||||
|
||||
end
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue