Thank you very much, your argumentation makes perfect sense. I find this type of discussions highly beneficial to the practice of this language. pedro
On Mar 23, 2:17 pm, Luke Smith <[email protected]> wrote: > On Mar 23, 2011, at 6:43 AM, Poetro wrote: > > > > > > > > > > > 2011/3/23 pnbv <[email protected]>: > >> Considering a single instance object: > >> app = { > >> foo: 'afoo', > >> bar: 'abar', > > >> callbackLib: { > >> replyFoo: function () { > >> console.log(this.foo); > >> }, > >> replyBar: function () { > >> console.log(app.bar); > >> } > >> }, > > >> doSomeThing: function (){ > >> this.callbackLib.replyFoo.call(this); > >> this.callbackLib.replyBar(); > >> } > >> } > > >> app.doSomeThing(); > > >> What would be the preferred way of doing this (if there really is a > >> need for nested objects:)? > >> Thanks, > >> pedro > > If you just want to get rid of the reference to this, you could do: > > > app = { > > foo: 'afoo', > > bar: 'abar', > > > callbackLib: { > > replyFoo: function () { > > console.log(app.foo); > > }, > > replyBar: function () { > > console.log(app.bar); > > } > > }, > > > doSomeThing: function (){ > > app.callbackLib.replyFoo(); > > app.callbackLib.replyBar(); > > } > > } > > app.doSomeThing(); > > > Although this would trigger errors in the following case: > > > bar = app; > > app = {}; > > bar.doSomeThing(); > > > As app is now no more. > > There's a failure case either way. > var doSomething = app.doSomething; > > doSomething(); // boom if the 'this' references are left in tact. > > I find it preferable for non-instance collections of functions (i.e. > object literals with methods as shown) to reference the object rather > than 'this' as they are often utility functions or apply to the > application as a whole, and are therefore more useful as function refs > that can be passed around or assigned to shortcut vars. Shortcut vars > can be compressed better as well. > > Short form: use 'this' in prototype methods, the containing var name > in "static" methods. As with most things, this is a guide, not a rule. > > L > > > > > > > > > -- > > Poetro > > > -- > > To view archived discussions from the original JSMentors Mailman > > list: http://www.mail-archive.com/[email protected]/ > > > To search via a non-Google archive, visit > > here:http://www.mail-archive.com/[email protected]/ > > > To unsubscribe from this group, send email to > > [email protected] -- To view archived discussions from the original JSMentors Mailman list: http://www.mail-archive.com/[email protected]/ To search via a non-Google archive, visit here: http://www.mail-archive.com/[email protected]/ To unsubscribe from this group, send email to [email protected]
