Subj : Re: associating an object with a Function object To : Brian Genisio From : Brendan Eich Date : Fri Mar 05 2004 11:56 am Brian Genisio wrote: > Hi all, > > In IE's JS engine, I can write the following: > > > > > It will execute the click() as if it were associated with the myButton > object. How non-standard is that -- a "bound method reference" or "delegate". Great, someone call ECMA and the w3c. We do this in LiveConnect for Java methods, but they're outside the scope of those specs, and doing otherwise makes no sense. > With the Mozilla spidermonkey engine, if I do this, clicker is stored > as a function object properly, but if executed as shown, the global > object is passed in as the object for the function. Yes, per ECMA-262. Standards, what a concept. > Is there any way to associate a specific object with a Function > object? That way, even if clicker() is executed in the global space, It isn't that clicker() is executed (called) from global code -- it's that 'clicker' names a global property. That decides what the |this| parameter binds to. > it is handed the myButton JS object, instead? > > My guess is not, since Mozilla fails with a prototype mismatch error, > as I would expect. > > Is there any way to do what I am talking about? Sure. In SpiderMonkey, make each button have a click method cloned (JS_CloneFunctionObject) from the prototype button click method, where the clone has the particular button as its parent. The prototype click method should be defined with JSFUN_BOUND_METHOD among its function flags (JS_DefineFunction). If you want a pure JS, ECMA-conforming approach, use closures: js> s = new String('hi') hi js> f = s.toString function toString() { [native code] } js> f() 3: TypeError: String.prototype.toString called on incompatible global js> function makeDelegate(o, m) {return function(){return m.apply(o, arguments);};} js> f2 = makeDelegate(s, f) function () { return m.apply(o, arguments); } js> f2() hi js> /be .