I’m trying to access to the method ‘render’ of my class, in another method of this same class.
But got the error
“Uncaught TypeError: Object [object Window] has no method ‘render’ “
Here is my code :
function myObject(options) {
this.top_offset = 100;
this.right_offset = 50;
};
myObject.prototype.render = function() {
alert ("render");
};
myObject.prototype.getContent = function(data, params) {
// do something with the data
alert('done');
// !not working here!
this.render();
}
Any idea what I’m doing wrong ?
Thanks !
EDIT
The example below is working, the difference with my real code is that I’m instanciating the object before an asynchronous call (get), and that the method of my object is used as a call back function.
// using the object
var o = new myObject('plop');
$.getJSON(url, toSend, function(data) {
}).success(function(e) {
myObject.getContent(e)
};
Update:
Meanwhile I’m seeing the code you’ve posted and I see you are already calling your callback on an anonymous function. I guess I have to do some more thinking, then.
As of now, I’m stumped.
Okay, so you’ve commented below the question that you are calling
getContent()through a callback.So you code looks somewhat like this, I assume:
It’s important to understand that JavaScript doesn’t really have methods. It has functions, and functions can be assigned as properties of objects, but that won’t mean these functions will in any way “belong” to these objects.
The
thisinside of a function, to put it simply, can either point to the object to the left of the dot when calling (not declaring) the function “as a method”; or the global object (window) if you call the function “not as a method”; or it can even point to some other object arbitrary object if you use tell the function to be bound or run to it — this can be done by using a few “methods” fromFunction.prototype:call,apply,bind.You can solve your problem by either creating an anonymous function which will call
getContent()with you object as it’s activation object, like this:or by explicitly binding your function to be run with your object as its
this:The second alternative is safer, because if the value of the
myObjvariable changes between the time this code runs and the time the callback is called, you may end up callinggetContent()on the wrong object.