How to make this refer to the constructor [duplicate] - javascript

This question already has answers here:
How to access the correct `this` inside a callback
(13 answers)
Closed 7 years ago.
I have the following code
function perso (image_mere, emplacement_x, emplacement_y, x, y, direction) {
this.source = image_mere;
this.sprite = createElement('div');
// some other properties
this.sprite.addEventListener('click', function() {
dindong = this;
(function(dindong) {
var canvas = document.createElement('canvas'),
context = canvas.getContext('2d');
alert(dingdong.image_mere)
})(dindong);
}, true);
};
As you can see, the keyword this refers to the sprite, howerver i want to refer to the object so i can get the properties :/
Thank you

You can use bind:
}.bind(this), true); //this is last line of your listener

Related

Passing method with class as a callback method to request animation frame [duplicate]

This question already has answers here:
How to access the correct `this` inside a callback
(13 answers)
Closed 3 years ago.
I'm working on an animation class:
class Animation{
constructor(id){
let canvas = document.getElementById(id);
this.frames = [];
this.step = 0;
this.ctx = canvas.getContext('2d');
this.img = new Image();
Object.assign(canvas, bound);
this.img.src = "vessle.svg";
}
run() {
log('run')
log(this)
let frame = this.frames[this.step];
this.ctx.globalCompositeOperation = 'destination-over';
// clear canvas
this.ctx.clearRect(0, 0, window.innerWidth, window.innerHeight);
//draw images
frame.forEach((pos)=>{
this.drawImage( pos)
})
window.requestAnimationFrame(this.run);
}
drawImage(pos){
//render stuff
}
}
When I pass this.run in requestAnimationFrame, it seems like the rest of the values from "this" are not included in the new context. For example this.frames is not defined when I run it the second time around.
When you passing the this.run in function parameter, it is just passing a callback function but not with this reference.
In this scenario you have to bind the reference of this
window.requestAnimationFrame(this.run.bind(this))
If you don't bind with this then inside the callback, this refers to that callback function (run()), not the Animation class.
For more see this reference how to bind the this reference.

Undefined Array in constructor with TypeError: Cannot read property '0' of undefined [duplicate]

This question already has answers here:
How to access the correct `this` inside a callback
(13 answers)
Closed 6 years ago.
My code creates a dispatcher from constructor ColorDispatcher. After window.onload, dispatcher.hoverOutHandler is regularly called after 1.5 sec. when changeBGColor called, the typeError described in the title shows; However I really cannot figure out why.
var ColorDispatcher = function() {
this.changeColorTimerID = 0;
this.rgbColorArray = new Array(0, 0, 0);
};
ColorDispatcher.prototype = {
hoverOutHandler: function() {
this.changeColorTimerID = window.setInterval(this.changeBGColor, 1500);
},
changeBGColor: function() {
//something went wrong here.
alert(this.rgbColorArray[0]);
},
};
var dispatcher = new ColorDispatcher();
window.onload = dispatcher.hoverOutHandler();
Change the following line:
this.changeColorTimerID = window.setInterval(this.changeBGColor.bind(this),1500);
setInterval called the function on the window scope therefor the array wasn't found. With .bind you can bind a function to a scope (in this case this).

this inside callback function [duplicate]

This question already has answers here:
How to access the correct `this` inside a callback
(13 answers)
Closed 8 years ago.
Here is my situation.
function Bird() {
this._canFly = true;
this._legs = 2;
this._flying = false;
}
Bird.prototype = {
Fly: function() {
if ( this.canFly ) {
layer.on('fly', function() {
this.setStrokeWidth(4); //this refers to layer(kinetic.js) object
this._flying = true; //this refers to Bird object
});
}//end if
} //end function
);
Here I need to access both layer object and bird object inside the callback function.
Can somebody tell me how to handle the above situation ?
var self = this
Cache a reference to this to refer to it when it changes context.

Requirejs Jquery prototype inheritance [duplicate]

This question already has answers here:
How to access the correct `this` inside a callback
(13 answers)
Closed 8 years ago.
I am trying to import jquery into my prototyped class which works initially in the constructor.
I lose my scope of jquery in the call to resizeCanvas event. It says the width() and height() function is undefined.
Is there a way I won't lose the jquery variable.
define(['jquery'], function($) {
function Canvas() {
this.canvas = document.getElementById('canvas');
this.context = this.canvas.getContext('2d');
this.rowbuild = $('#rowbuild');
}
Canvas.prototype.addResizeListener = function() {
window.addEventListener('resize', this.resizeCanvas, false);
};
Canvas.prototype.resizeCanvas = function() {
this.canvas.width = this.rowbuild.width();
this.canvas.height = this.rowbuild.height();
};
return Canvas;
});
You need to bind the listener to the correct context object using bind or $.proxy.
window.addEventListener('resize', this.resizeCanvas.bind(this), false);
Besides, why are you using addEventListener if you are already using jQuery?

Extend onclick function to javascript class [duplicate]

This question already has answers here:
Class methods as event handlers in JavaScript?
(5 answers)
Closed 9 years ago.
I'd like to include an onclick event in a JavaScript class, but since onclick is a function inside of the class the this variable won't work properly.
How can I modify/output the this variable from the onclick function?
img = new image();
function image() {
this.width = 400;
this.height = 600;
document.getElementById('button').onclick = function()
{
alert(this.width); // alerts undefined
};
}
See JSfiddle here: http://jsfiddle.net/ZghRv/
You can use bind() to create a new function that will have this set to the object you pass to bind().
img = new image();
function image() {
this.width = 400;
this.height = 600;
document.getElementById('button').onclick = (function()
{
alert(this.width); // alerts undefined
}).bind(this); // <--- Add bind() here to pick the value of 'this' inside onclick
}
Check out JavaScript Function bind for more info and interactive examples.
You can also give reference to the outer this
Updated Fiddle:
http://jsfiddle.net/ZghRv/3/

Categories

Resources