This question already has answers here:
How to access the correct `this` inside a callback
(13 answers)
Closed 5 years ago.
My createCon function uses this to set the con for this object. I am getting this to be undefined. Error: Can not set property of 'con' of undefined.
What is the best of being able to reference this from the objects functions?
class parent {
constructor(stringA, stringB){
this.config = {};
this.con = {};
}
}
class child extends parent {
constructor(stringA, stringB) {
super(stringA,stringB)
this.config = {
full : stringA+stringB
}
}
createConn(){
var con = con(this.config.full);
con.connect(function(err){
if(!err) this.con = con;
})
}
}
You are using the this keyword inside of a function. this is not like other OOP languages and refers to a 'context', which can change based on the execution of the function.
You want to use an arrow function, which will lexically bind (i.e, preserve) the this of the context where the arrow function is defined.
createConn(){
var con = con(this.config.full);
con.connect((err) => {
if(!err) this.con = con;
})
}
Related
This question already has answers here:
How to access the correct `this` inside a callback
(13 answers)
Closed 4 years ago.
Why am I unable to return the element_id in the run function? The script works if I set it as let self = this; function(){ self.run() }
Doesn't work:
class clickin {
constructor(element_id) {
this.element = document.getElementById(element_id);
this.element.addEventListener('click', this.run);
}
run() {
alert('Element id: ' + element_id);
}
}
Works:
class clickin {
constructor(element_id) {
this.element = document.getElementById(element_id);
let self = this;
this.element.addEventListener('click', function(){
self.run();
});
}
run() {
alert('Element id: ' + element_id);
}
}
Using the addEventListener object, you are setting a callback function which will be called when the event is fired. So, it runs in a different context than your constructor function. In that case, the "caller(this)" object changes, and thus, this.run you mentioned above won't work.
But, when you assign "clickin" class object to a variable "self", you are able to run because self is available in callback function as a closure, and when event handler executes, it is able to access that "clickin" object.
You might want to look deeper into below topics for better understanding.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this
https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener
Alternatively, if you don't want to deal with class properties (as mentioned in the comments), just use an arrow function in the constructor instead:
class clickin {
constructor(id) {
this.element = document.getElementById(id);
this.element.addEventListener('click', () => this.run(id));
}
run(id) {
alert('Element id: ' + id);
}
}
const c = new clickin('a');
<div id="a">aaa</div>
This question already has answers here:
How to access the correct `this` inside a callback
(13 answers)
Closed 4 years ago.
I have a class and it has a constructor.
I assign a class variable by this.something and it is not being accessed in some another function inside the same class.
Following is my class
class A {
some_func() {
console.log(this.var1); // this is giving undefined
}
constructor(socket, var1) {
this.socket = socket;
this.var1 = var1;
this.socket.on('some event', some_func);
}
}
Inside the some_func function the variable is undefined.
How do i fix that?
I don't see a problem with your code. Are you definitely instantiating the variable before using the method? As shown below
class A {
constructor(socket, var1) {
this.socket = socket;
this.var1 = var1;
//this.socket.on('some event', this.some_func);
}
some_func() {
console.log(this.var1); // this is giving undefined
}
}
var instanceA = new A('socket', 'var')
instanceA.some_func() // Returns 'var'
This question already has answers here:
Nested Object Literal Access Parent
(3 answers)
Closed 6 years ago.
I have created an object within a prototype and I am trying to access a variable from the constructor with this, but the alert is returning undefined.
Constructor
function Example() {
this.param1 = 'test';
}
Prototype
Example.prototype = {
constructor: Example,
obj: {
sample:function() {
alert(this.param1); // error undifined
}
}
};
Instantiate
var o = new Example();
o.obj.sample();
Any advice would be much appreciated.
You can do this though
function Example() {
this.param1 = 'test';
}
Example.prototype = {
constructor: Example,
obj: {
sample:function(){
alert(this.param1); // error undifined
}
}
};
var o = new Example();
o.obj.sample.call(o); // <--- I use "call" to supply the context. In this case, the context would be "o"
// or
o.obj.sample.bind(o)(); // or "bind" the context, in this case "o"
This question already has answers here:
How to access the correct `this` inside a callback
(13 answers)
How do I write a named arrow function in ES2015?
(8 answers)
Closed 7 years ago.
For example in the Class constructor:
Socket.on('user:join', onUserJoin);
'onUserJoin' is declared as a method of the class but is being called by socket.io so the 'this' is not my Class. A way to resolve this is to use the '=>' function.
example:
Socket.on('user:join', (data)=>{
this.isOnline = true;
});
Now 'this' is my class, but how do I reference this anonymous function to unsubscribe ?
socket.removeListener('user:join', ????);
I did try this:
let self;
class RoomController {
constructor() {
self = this;
}
...
}
and reference the self in the methods but the self was being shared across sockets...
naming the anonymous function could solve it but I preferred for my case the bind option.
You can use Function.prototype.bind.
Socket.on('user:join', onUserJoin.bind(this));
This ensures that onUserJoin has the correct context, which will be the instance of your class.
You can always bind the arrow functions to the names.
For example,
class RoomController {
constructor() {
this.flag = true;
}
// Assign the arrow function to the name `setFlag`
setFlag = (v) => this.flag = v;
}
let r = new RoomController();
function tester(func) {
func(false);
console.log(r.flag);
// false
func(true);
console.log(r.flag);
// true
}
// Now you can pass the function around, `this` will still refer the object `r`
tester(r.setFlag);
This question already has answers here:
How to access the correct `this` inside a callback
(13 answers)
Closed 8 years ago.
Consider my following object and method:
function ModalPopupWindow() {
this.Modal = false;
function __InitModalPopUp(height, width, title) {
if(this.Modal != true){
divOverlay.onclick = function() { window.parent.HideModalWindow(); };
}
}
}
Whey I try to assess this.modal property inside the init function on a ModalPopupWindow object, 'this' is referencing to Window, not the object's property. How can I get that value?
There are several techniques, including a method named bind(). Another approach is to create a variable and bind it to the parent context before the function is called. I have seen people use a variable named underscore this (_this)
function ModalPopupWindow() {
//Capture the correct "this"
var _this = this;
this.Modal = false;
function __InitModalPopUp(height, width, title) {
//Use _this here
if(_this.Modal != true){
divOverlay.onclick = function() { window.parent.HideModalWindow(); };
}
}
}
I recommend this article if you want to learn more about how JavaScript works and how to use bind().
http://javascriptissexy.com/javascript-apply-call-and-bind-methods-are-essential-for-javascript-professionals/