This question already has answers here:
How to access the correct `this` inside a callback
(13 answers)
Closed 8 years ago.
I want to make a select option for animations, so whatever type is selected, it's shown on the canvas.
So i make each animation as a "class" :
(function (exports) {
function animationA() {}
animationA.prototype.init = function(){}
animationA.prototype.draw = function(){}
exports.animationA = animationA;
})(this);
Then in the main js:
var a = new animationA();
function setup() {
a.init();
}
function update(callback) {
requestAnimationFrame(function () {
update(callback);
});
console.log(this);
callback();
}
setup();
update(a.draw);
I found error occurs in the update(a.draw). It cannot access the properties of a in this line of code.
I wonder if this is a javascript scope problem?
Thanks.
You need to create a reference to the context you want to refer to inside the callback before you call requestAnimationFrame, just like you would with a normal event callback.
Var that = this;
requestAnimationFrame(function(){
that.doSimething();
});
Related
This question already has answers here:
Accessing an object's property from an event listener call in JavaScript
(6 answers)
Closed 2 years ago.
I have the following JS object in my code:
var myLibrary = {
name: "John",
// Functions
func1: function() {
alert(this.name);
},
func2: function() {
this.func1();
},
// On DOM loaded
onDOMLoaded: function() {
this.func1();
this.func2();
}
}
document.addEventListener('DOMContentLoaded', myLibrary.onDOMLoaded);
When I reference this code using a script tag, I get the following error (in reference to the call in func2):
Uncaught TypeError: this.func1 is not a function
This is especially weird because if I call the functions from within the DOM, they work perfectly. For example:
<button onclick="myLibrary.func1()">Func 1</button>
<button onclick="myLibrary.func2()">Func 2</button>
Clicking on the buttons does exactly what I want them to. What am I doing wrong here? And how can I fix this issue? Thanks for any help!
A demo can be found here: https://jsfiddle.net/gLxvsze0/
You should read about this is JS.
When you call myLibrary.func1() the function will be called with myLibrary context. But when you call just func1 (ie func1 = myLibrary.func1; func1()) this will be called with global Window context.
To solve your problem, you can use bind method, that creates new function linked with provided context:
document.addEventListener('DOMContentLoaded', myLibrary.onDOMLoaded.bind(myLibrary));
I think the simplest solution to the context issue is...
document.addEventListener('DOMContentLoaded',() => { myLibrary.onDOMLoaded(); });
This question already has answers here:
var functionName = function() {} vs function functionName() {}
(41 answers)
Closed 7 years ago.
I've recently gone into developing with AngularJS. It's confusing to me the different between these two:
$scope.myScope = function () {
var x = 'do something with variable here';
$scope.anotherScope = x;
};
and
function myFunction () {
var x = 'do something with variable here';
$scope.anotherScope = x;
}
They both seem to be able to do the same thing (I use them a lot inside controllers). Is there a best practice for when and where to use these two?
$scope.myScope = function () {};
This means your function is a property of the scope object. So you can use it in your controller , html page even in your app. it can be referenced in different modules in the same app. so you just call it in your html page using the function name directly either onclick or onchange , anyhow depending on your need.
the other definition can only be used in your controller and is not the scope of your app. however if you define your function using "this.myScope = function(){};" then you can call the function in your html by using your controller. like ng-click = "controllerName.myScope();"
the main difference is i nwhich scope the function belongs to and where all you can reference the function.
hope it helps !!!!
As mourycy already mentioned, you should use the form
$scope.myScopeFunction = function () {
...
};
only for functions which you want to call via the scope object. This is needed for function calls within your views.
For example:
<button ng-click="myScopeFunction()" />
which calls the function myScopeFunction of the current $scope object.
If you don't need to be able to call a controller method from "outside" you should use the following form:
function myFunction() {
...
};
$scope.myScop = function(){
...
};
is a function you can execute from the HTML controller.
function foo(){
...
}
is a function you can only execute on the controller's JS file.
This question already has answers here:
Can I override the Javascript Function object to log all function calls?
(6 answers)
Closed 5 years ago.
For debugging purposes, I was wondering if there's some way in which I can create a piece of code to run whenever a javascript function is called - like adding something to Function.prototype or Function.constructor etc.
You could use a "decorator-like".
Something as simple as executing
var yourFunction = function { // do stuff };
var yourSecondFunction = function { // do stuff };
var myDecorator = function( callback )
{
// do your stuff
// ...
// then execute function
callback();
};
// usage
myDecorator( yourFunction );
myDecorator( yourSecondFunction );
I don't think overwriting the prototype of Function is a good idea.
This question already has answers here:
How to access the correct `this` inside a callback
(13 answers)
Closed 8 years ago.
I have written some namespaced javascript and I'm having trouble binding to window events (such as scroll, resize) and retaining access to my instance of the app, for example:
var app = new function() {
this.init = function() {
var self = this;
window.onresize = self.resize;
};
this.resize = function() {
var self = this;
console.log(self); // Gives me the window!
};
};
app.init();
I'd rather not have to declare the function then and there with window.onresize = function()..., because I want to be able to call my app.resize() function independently too. Is there a better way to do this within the scope of my app?
Niet the Dark Absol's answer is correct and shorter, but learning about call and apply to set the value of this inside functions changed my life! Maybe it will help you too:
window.onresize = function() {
// calls self.resize() with the value of `this` set to `self`
self.resize.call(self);
};
No reason why you can't do both:
window.onresize = function() {self.resize();};
// calls `self.resize` with the context of `self`
This question already has answers here:
How does "this" keyword work within a function?
(7 answers)
Closed 8 years ago.
I have a JS object that in pseudo code is doing this:
function myObj {
// in constructor
... initialise vars
... call $.Ajax to fetch view from server
function AjaxCallBack() {
// load the DOM with the HTML result
$('#dialog').html(ajax.result);
// try to register a change handler
$("#dialog :input").change(this.formChangeEvent);
}
this.formChangeEvent = function(){
... do stuff
}
}
The problem is that in the AjaxCallBack, 'this' is not myObj object, but rather the 'window' object and can't resolve the function
The only way I've been able to get around this problem is to have the receiver of the object call back into a separate function of myObj and register the event
objInstance = new myObj();
objInstance.registerEventHandler();
I've tried a few other things, but I'm obviously missing something basic.
If I understand your question then you can hold this to any variable like var thisObj=$(this) . Now you can use thisObj.formChangeEvent. Hope this will help.
Try this:
function myObj {
// in constructor
... initialise vars
... call $.Ajax to fetch view from server
var oThis = this; // oThis is object this which points to myObj
function AjaxCallBack() {
// load the DOM with the HTML result
$('#dialog').html(ajax.result);
// try to register a change handler
$("#dialog :input").change(oThis.formChangeEvent);
}
this.formChangeEvent = function(){
... do stuff
}
}
It will do the trick.