Reputation: 304
I'm making a js canvas plugin, and I made this object:
function MyObject(argument) {
var self = this;
var callback = argument.callback;
this.onRequestAnimationFrame = function() {
callback(self);
}
this.myFunction = function (){
return false;
}
}
and I call it like this
var customObject = new MyObject({
callback: function(instanceClass){
instanceClass.myFunction();
}
})
The problem is, I must get the instance class and call a function from it, but I get "myFunction is not a function" from the console.
Upvotes: 0
Views: 189
Reputation: 703
When we make a constructor call, if we are not returning any object then function returns a 'this' object which is in its lexical scope.
when you write this,
var customObject = new MyObject({
callback: function(instanceClass){
instanceClass.myFunction();
}
});
function MyObject returns its 'this' object.
So, we can call 'onRequestAnimationFrame' function which in return call the callback.
customObject.onRequestAnimationFrame();
jsbin link: http://jsbin.com/foxupakihi/edit?js,console
Upvotes: 0
Reputation: 1753
You don't access "this" from outside the object.
The way you have written this, you need to instance the object, at which point myFunction will be a method of the object.
"this" is not a variable, but a keyword.
function MyObject(argument) {
var self = this;
var callback = argument.callback;
this.onRequestAnimationFrame = function() {
callback(self);
}
this.myFunction = function (){
return false;
}
}
function callback (caller) {
console.log(caller.myFunction());
};
var a = new MyObject({callback : callback});
Upvotes: 2