How can I access "self" in a JavaScript class? [duplicate] - javascript

This question already has answers here:
Losing "this" context in JavaScript when passing around members [duplicate]
(3 answers)
What is a good way to automatically bind JS class methods?
(5 answers)
Closed 4 months ago.
Note: I do not want to re-bind the this keyword. I would like for this to reference the calling object. I would, however, also like to be able to reference the instance of the class in which my method is defined. How can I access the instance?
In JavaScript, the this keyword refers to the calling object. So, when I define a class:
class A {
x = 5;
printx() {
console.log(this.x);
}
}
Then when I call the printx method directly from an instance of A, I get 5:
a = new A();
a.printx();
But when I call printx from a different context, this.x isn't a.x, it might be window.x or something else:
b = a.printx;
b(); // TypeError: this is undefined
I want to define printx in such a way that calling b will console.log(5). I.e., I want to get the self behavior from Python. How do I refer to self in JavaScript?

Use function.prototype.bind to bind the function to the context when you assign b
class A {
x = 5;
printx() {
console.log(this.x);
}
}
let a = new A()
let b = a.printx.bind(a)
b()

Related

.bind not working with es6 class instance [duplicate]

This question already has answers here:
Can you bind 'this' in an arrow function?
(14 answers)
Closed 2 years ago.
using the bind documentation, if i replace the object (defined as module in their example), with an es6 class instance, it does not bind.
here are the docs...
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Function/bind
and here is my code...
class Foo {}
let foo = new Foo()
let fooVar = 'foo var'
let fooFunc = () => {
return this.var
}
foo['var'] = fooVar
fooFunc.bind(foo)
foo['func'] = fooFunc
// i expected this to return 'foo var', but instead get 'undefined'
foo.func()
how can i essentially add an instance method to an existing instance, and have it bind properly?
If you read the documentation about arrow function you will see that:
Does not have its own bindings to this or super, and should not be used as methods.
Therefore you cant bind a new this if it doesnt have one

Outside scope this key word in JavaScript? [duplicate]

This question already has answers here:
How does the "this" keyword work, and when should it be used?
(22 answers)
Closed 5 years ago.
I am not sure why I'm getting undefined with the code below. I tried to declare a variable under the say method var _this = this and then console.log out _this.name but it did not work.
let dog = {
name: 'doggo',
sayName() {
console.log(this.name)
}
}
let sayName = dog.sayName
sayName()
window.name="test";
sayName();//test
Executes the function in window context so this is window. You may want to keep the dog context either through passing it:
sayName.call(dog);//doggo
Or through keeping a bound function:
let sayName = dog.sayName.bind(dog);
sayName();//doggo

'var a' vs 'this.a' in function block [duplicate]

This question already has answers here:
How does the "this" keyword work, and when should it be used?
(22 answers)
What is the scope of variables in JavaScript?
(27 answers)
Closed 5 years ago.
I tried to search it on internet but didn't got any answer. Why access of two variables before declaration have two different outputs:
function test() {
console.log(a); // prints 'undefined'.
console.log(b); // prints 'b is not defined'.
var a = 5;
this.b = 10;
}
when you declare var variable inside the function then that variable is limited to that function. That mean scope of that variable is limited to that function so you can't access that variable outside of that function.
But if you use this then it can be access through outside but then again you need to create a object of that class/function and access trough it.
function test() {
var a = 5;
this.b = 10;
this.printB = function(){
return this.b;
}
this.printA = function(){
return a;
}
}
var obj = new test();
console.log(obj.a)
console.log(obj.b)
console.log(obj.printA())
console.log(obj.printB())
when you write a variable with var like var a it become a function
level variable. so now a is a variable which is present there before consol.log(a) and its not given a value so its undefined for b there is no variable defined with name b before it called.
And which all variables are defined with var will be function level variable and will be created before anything else in the function. so a will be present in the function at the starting itself.
and here this will be holding the object of Windows.
First of all, you are trying to examine the variables before you declared them.
This is the correct order:
function test()
{
var a=5;
this.b=10;
console.log(a); // Should print 5
console.log(b); // Should print undefined
console.log(this.b); // Should print 10
}
Second, regarding your question, declaring a var inside your function, make is a local private variable inside your function.
declaring this.b, will cause b to be in a different scope, and b for itself as undefined. If you want to use b inside the function, use this.b.

Why(How) does value of 'this' changes when a callback is called from inside the function? [duplicate]

This question already has answers here:
How to access the correct `this` inside a callback
(13 answers)
How does the "this" keyword work, and when should it be used?
(22 answers)
Closed 6 years ago.
I understand that there are quite a few question similar to this one but I couldn't find any which answers why or may how the context(value) of this changes when a callback function is called from inside the object function
like this
var obj = {
objproperty: "this is a property of obj",
func1: function(x,cb){
console.log(this) // refers to obj
var output_value = x + 20;
cb(output_value);
}
};
obj.func1(123,function(output_value){
console.log(output_value);
console.log(this); // does this refers to window or undefined??
});
as far as I understand the value shouldn't 'this' in third console.log be referring obj? as it called on the obj Object ?
as it called on the obj Object ?
No, it isn't.
cb(output_value);
There is nothing to the left of cb so it is called in the default context.
Your callback is called like this:
cb(output_value);
There's no object context in that function call, so the value of this will be either window (or the global context) in non-strict mode, or undefined in strict mode.
If you want to make sure that the callback has a this value that matches that in the context in which it's called, you can use .call():
cb.call(this, output_value);

use of "that" keyword in javascript [duplicate]

This question already has answers here:
What does 'var that = this;' mean in JavaScript?
(6 answers)
Closed 10 years ago.
I have few javascript that has used the keyword "that" extensively.
I see a lot of posts talking about the javascript keyword "this".
I wanted to understand the meaning of this key word in javascript context and it's visibility/scope.
Something like
that.someFunctionaName(someParameter)
What does it mean?
I understand the keyword "this" always points to the owner of the current object.
that is not a keyword in JavaScript. I suspect the code that you have is using something in the class to define an instance of itself. For example:
function myClass()
{
var that = this;
}
By doing this, you can ensure you're referencing the object, and not another element. For example, consider the following sample:
function myClass()
{
var that = this;
$('.myele').click(function() {
// 'this' refers to the element that was clicked.
// 'that' still refers to the myClass() object.
});
}

Categories

Resources