I want to do this in Javascript:
function Z( f )
{
f();
}
function A()
{
this.b = function()
{
Z( function () { this.c() } );
}
this.c = function()
{
alert('hello world!');
}
}
var foo = new A();
foo.b();
It can be accomplished this way:
function Z( f )
{
f();
}
function A()
{
var self = this;
this.b = function()
{
Z( function () { self.c() } );
}
this.c = function()
{
alert('hello world!');
}
}
var foo = new A();
foo.b();
Is there a better way?
Keeping a reference to the parent (like you have) is a good approach, however for your specific example there's no need for the anonymous wrapper, you can pass the function directly, like this:
var self = this;
this.b = function()
{
Z(self.c);
}
You can test it out here, and without this wrapper there's actually no need for the self
variable, you can just use this
directly, like this:
this.b = function()
{
Z(this.c);
}
You can test that version here.
Since there seems to be some confusion in the comments below, the above code maintains this
for the question, if you want to maintain the this
/context inside the callback as well, use .call()
like this:
this.b = function()
{
Z.call(this, this.c);
}
And for Z
:
function Z( f )
{
f.call(this);
}
You can test it here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With