this argument to lambda revisited

9 views
Skip to first unread message

Charles Lowell

unread,
Jul 3, 2012, 12:39:06 PM7/3/12
to javascript-...@googlegroups.com
I think I've found a nice solution to the whole problem of how the `this` object is passed in a function. I've implemented it on the latest Racer beta, but wanted to share it with a larger audience.

Basically, each context has a instance of Access, which has methods through which every 


call(receiver, *args)
methodcall(receiver, *args)

These,  by default, delegate to `obj`, so the Access class looks like


class Access
  def methodcall(code, this, *args)
code.methodcall(this, *args)
  end
end

and then we have a module that gets included into Proc

module Access::Proc
  //ignore `this`
  def methodcall(this, *args)
    self.call(*args)
  end
end

class Proc
  include Access::Proc
end


This way, you can set behavior for Procs inside a JS::Context at every possible level. At the object level:

//accept `this` parameter when invoking a code block
module AcceptThis
  def methodcall(this, *args)
    call this, *args
  end
end


cxt = JS::Context.new
say = cxt['say'] = proc {|this, one, two| }

//accept `this` parameter, but only for this object
say.extend AcceptThis

//accept `this` parameter for all procs inside this context

context.access.extend(Module.new do
  def methodcall(code, this, *args)
    code.extend AcceptThis
    super
  end
end)

//accept `this` parameter globally for all procs in the process

class Proc
  include AcceptThis
end


It seems pretty clean and flexible.

cheers,
Charles


Charles Lowell 
thefrontside.net | twitter: @cowboyd | github: cowboyd




Reply all
Reply to author
Forward
0 new messages