common reasons for javascript reference error with prototype
I am new to the prototype framework and fairly new to Javascript (it's been a long while sicne any heavy javascript work). I have defined a class that is calling another method within it and I keep getting a ReferenceError "getLabel is not defined". getLabel is another class method that I am trying to call. Here is the code where I am calling it:
var title = new Element('td');
title.addClassName(label_class);
title.addClassName('scorecard_tee_title');
title.appendChild(new Element('span').update(getLabel(tee, true)));
I have tried using this.getLabel as well but to no avail. I'm guessing that I have a syntax error in my class (which is too large to place here), but can't find what's wrong.
What should I be checking for? Are there any common reasons for this error to be thrown that I should keep in mind when using Prototype?
Thanks!
UPDATE: I pulled the getLabel function out of my class and it works fine,开发者_Python百科 which leads me to believe that it is in some way related to the getLabel function being passed into or evaluated as a member of the class and not a standalone function. Still not sure what I'm doing wrong though.
It is my understanding (which I admit, is pretty limited when it comes to object oriented programming), that you don't call methods as functions directly. They need to be called as methods for an object. For instance:
getLabel(foo);
If getLabel is method of a class, it modifies an object. In your example, you are not modifying an object, so what is getLabel actually getting the label for? If it's getting the label of tee
, then you'd want:
tee.getLabel();
But if I'm wrong, somebody let me know and I'll delete this.
You need to reference getLabel somehow, either classInstance.getLabel() or this.getLabel(). I see you already tried the later so I'm assuming this code is not running inside the same class as getLabel() belongs to?
The problem with the undefined methods was being caused because the method that was calling them were being called from anonymous function. Binding the anonymous function to (this) from where it was being created works.
I realized this when I looked at 'this' in Firebug and realized it was pointing to Window and not Object.
精彩评论