Reputation: 1616
var x = (arg1, arg2) {
this.y = arg1;
this.z = arg2;
}
x.prototype.a = function() {
var self = this;
some_obj1.on('data', function() {
self.y = 'new y value';
});
}
x.prototype.b = function() {
var self = this;
some_obj2.on('data', function() {
self.z = 'new z value';
});
}
Is there any way to declare self as an instance variable (without using 'this' obviously) so that it doesn't need declaring within every function? So for example the declaration of 'a' would be:
x.prototype.a = function() {
ob2.on('data', function() {
self.z = 'some new value';
});
}
Hopefully this example is clear enough, it's not tested (written on the fly when asking the question) and more pseudo code but should get the point across..
Upvotes: 2
Views: 158
Reputation: 28511
The best thing to do is to partially apply arguments. The below is a cross browser implementation of the newer Function.prototype.bind
. project.bind
, using the below implementation, will use native Function.prototype.bind
if it is available or the custom implementation if the native one is not available.
Update I created a working Fiddle.
project = {};
project.bindJs_ = function(fn, selfObj, var_args) {
if (!fn) {
throw new Error();
}
if (arguments.length > 2) {
var boundArgs = Array.prototype.slice.call(arguments, 2);
return function() {
// Prepend the bound arguments to the current arguments.
var newArgs = Array.prototype.slice.call(arguments);
Array.prototype.unshift.apply(newArgs, boundArgs);
return fn.apply(selfObj, newArgs);
};
} else {
return function() {
return fn.apply(selfObj, arguments);
};
}
};
// A router for the native Function.prototype.bind
project.bindNative_ = function(fn, selfObj, var_args) {
return /** @type {!Function} */ (fn.call.apply(fn.bind, arguments));
};
project.bind = function() {
if (Function.prototype.bind &&
Function.prototype.bind.toString().indexOf('native code') != -1) {
project.bind = project.bindNative_;
} else {
project.bind = project.bindJs_;
}
return project.bind.apply(null, arguments);
};
Now you can do this:
x.prototype.a = function() {
ob2.on('data', project.bind(function() {
// the this. object inside the function will now point to x.
this.z = 'some new value';
}, this, any, argument, you, want, to, pass));
}
Upvotes: 2
Reputation: 32598
No, you can't. You'd need to modify the scope chain in some way to avoid using this
at all. A slightly cleaner way would be to use Function#bind
to specify this
.
x.prototype.a = function() {
ob2.on('data', function() {
this.z = 'some new value';
}.bind(this));
}
Upvotes: 2