I’m a newbie to javascript and I need some help.
I was trying to sum radius by function, but got an undefined error:(
function sumWithFunction(func, number) {
return func() + number;
}
function Circle(X, Y, R) {
this.x = X;
this.y = Y;
this.r = R;
}
Circle.prototype.getRadius = function () {
return this.r;
}
Circle.prototype.increaseRadiusBy = function(number) {
this.r = sumWithFunction(this.getRadius, number);
}
function addFivetoIt(func) {
func(5);
}
var MyCircle = new Circle(0, 0, 10);
addFivetoIt(MyCircle.increaseRadiusBy);
The problem is that you’re passing a function a reference to another function, and the passed function is therefore losing scope! Here’s the offending line:
JavaScript objects are in some ways simpler than they appear. When you added the
getRadiusmethod to theCircleprototype, you were not defining a class method like you would in classical OO. You were simply defining a named property of the prototype, and assigning a function to the value of that property. When you passthis.getRadiusas an argument to a static function, likesumWithFunction, the context ofthisis lost. It executes with thethiskeyword bound towindow, and sincewindowhas norproperty, the browser throws an undefined error.Put another way, the statement
this.getRadius()is actually saying “execute the function assigned to thegetRadiusproperty ofthis, and execute it in the context ofthis. Without calling the function explicitly through that statement, the context is not assigned.A common solution to this is to add an expected argument to any function which receives another function, for context.
A simpler, but less robust solution would be to declare a function inline that can access a context reference in the local closure.
But by far the simplest solution is to use a newer feature of ECMAScript, a function method called
bind. It is explained well here, including the fact that it is not supported by all browsers. That’s why a lot of libraries, like jQuery, Prototype, etc., have cross-browser function-binding utility methods like$.proxy.