Hi, > But it's really inelegant. How am I supposed to handle this?
Pretty much like that, except I haven't reassigned the property like that. It *should* be fine, you'll create an own property 'f' on the instance (rather than an inherited one from the prototype) that's bound. But it bothers me and I can't give you a good reason for it. :-) I've done that sort of thing before (keep a bound copy around on the instance, if I'm going to reuse it), I've just for some reason always used a different prop name, I guess so I'm not in doubt whether I've bound it. But doing it in the initializer like you have, there wouldn't be any confusion... Also, the odds are pretty high you just want #bind, not #bindAsEventListener.[1] [1] http://proto-scripty.wikidot.com/prototype:tip-you-probably-don-t-need-bindaseventlistener HTH, -- T.J. Crowder tj / crowder software / com Independent Software Engineer, consulting services available On Aug 3, 2:39 pm, Cédric <[email protected]> wrote: > Hello, > > I'm trying to use the Class methods to manage my object hierarchy on > my current project, but I have some trouble with the "this" keyword in > conjonction with Class.create. > > Here is a piece of plain-js code using prototypes to get inheritance: > > var Super1 = function () { > this.fu = "bar"; > > } > > var Sub1 = function () { > this.baz = "bat"; > this.f = function () { > alert("classic:"+this.fu+this.baz); > }.bind(this); > document.observe("click", this.f);}; > > Sub1.prototype = new Super1(); > new Sub1(); > > Here is my attempt at mimic this with Class.create: > > var Super2 = Class.create({ > fu: "bar" > > }); > > var Sub2 = Class.create(Super2, { > baz: "bat", > f: function () { > alert("Class:"+this.fu+this.baz); > }.bindAsEventListener(this), > initialize: function () { > document.observe("click", this.f); > }}); > > new Sub2(); > > But of course it doesn't work, f in bound to window, not the object > create by new. The only way I found is: > > var Super2 = Class.create({ > fu: "bar" > > }); > > var Sub2 = Class.create(Super2, { > baz: "bat", > f: function () { > alert("Class:"+this.fu+this.baz); > }, > initialize: function () { > this.f = this.f.bindAsEventListener(this); > document.observe("click", this.f); > }}); > > new Sub2(); > > But it's really inelegant. How am I supposed to handle this? --~--~---------~--~----~------------~-------~--~----~ You received this message because you are subscribed to the Google Groups "Prototype & script.aculo.us" group. To post to this group, send email to [email protected] To unsubscribe from this group, send email to [email protected] For more options, visit this group at http://groups.google.com/group/prototype-scriptaculous?hl=en -~----------~----~----~----~------~----~------~--~---
