On Mar 23, 11:43 pm, Poetro <[email protected]> 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.
Or wait for ES5 to become ubiquitous and use Function.prototype.bind:
var foo = (function() {
var o = function(s) {
alert(s);
}
return {
yell: (function(t) {
this(t.toUpperCase());
}).bind(o)
}
})();
foo.yell('hi');
var yell = foo.yell;
yell('hi');
Works in Chrome, maybe some others, not Firefox or IE so not useful
yet.
--
Rob
--
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]