JavaScript field access from anonymous function [duplicate] - javascript

This question already has answers here:
How does the "this" keyword work, and when should it be used?
(22 answers)
Closed 3 years ago.
how can I access a fiel from within an anonymous function inside a method?
like in this example:
class Something {
constructor (){
this.gax = “gax”;
}
doSomething(){
(function () {
console.log(this.gax);
}());
}
}
new Something().doSomething();
this will result in an error that "this" is undefined.
thank you very much in advance, I could not find an answer in the web after searching for hours.
best,
lev

In your anonymous function, this is bound to the function; it no longer refers to the class.
Use an arrow function instead, which doesn't have it's own this binding.
class Something {
constructor (){
this.gax = "gax";
}
doSomething(){
(() => {
console.log(this.gax);
})();
}
}
new Something().doSomething();
Alternatively, you could use something like .call(), .apply(), or .bind():
class Something {
constructor (){
this.gax = "gax";
}
doSomething(){
(function() {
console.log(this.gax);
}).call(this);
}
}
new Something().doSomething();

class Something {
constructor (){
this.gax = "gax";
}
doSomething(){
(function () {
console.log(this.gax);
}).apply(this);
}
}
new Something().doSomething();
You can use apply method. The apply() method calls a function with a given this value

Related

Javascript "this" not set in function that was passed around [duplicate]

This question already has answers here:
"This" within es6 class method [duplicate]
(1 answer)
How to access the correct `this` inside a callback
(13 answers)
Closed last month.
I have a class, in where I have a method that creates a function to be called by some third party library. Inside the function I want to call class members, but the "this" keyword is not set anymore at the moment the function is called. How can I get the this keyword to work inside the function?
I have an oversimplified example:
class myclass
{
printIt(x) {
console.log(x);
}
getFunc() {
return function(x) { this.printIt(x); };
}
}
(new myclass).getFunc()("test");
TypeError: Cannot read properties of undefined (reading 'printIt')
And I also have a solution which I am not happy with, and which I expect can be done in a more elegant way:
class myclass
{
printIt(x) {
console.log(x);
}
getFunc() {
let self = this;
return function(x) { self.printIt(x); };
}
}
(new myclass).getFunc()("test");
class myclass {
printIt(x) {
console.log(x);
}
getFunc() {
return function(x) {
this.printIt(x);
}.bind(this);
}
}
(new myclass).getFunc()("test");

Why can't I access `this` within an arrow function? [duplicate]

This question already has answers here:
What does "this" refer to in arrow functions in ES6?
(10 answers)
Closed 7 years ago.
This code below should work as expected, and log "meow", here an example.
function Cat () {
this.animalNoise = 'meow'
}
Cat.prototype.sound = () => {
console.log(this.animalNoise)
}
let cat = new Cat()
cat.sound()
It doesn't work, this error appears TypeError: Cannot read property 'animalNoise' of undefined and when you convert the arrow function to an actual function declaration it works. It seems like with the arrow function, I no longer have access to this. What's going on here?
To be clear, the above code does not work where the following does, and I'm very curious why.
function Cat () {
this.animalNoise = 'meow'
}
Cat.prototype.sound = function() {
console.log(this.animalNoise)
}
let cat = new Cat()
cat.sound()
Arrow functions perform lexical binding and uses the surrounding scope as the scope of this. For example, imagine (for some weird reason) you define Cat inside of a Dog constructor.
function Dog() {
// do dog like things
function Cat() { ... }
Cat.prototype.sound = () => {
// this == instance of Dog!
};
}
So whatever the surrounding scope is becomes the scope of an arrow function.

How to pass "this" to another object in javascript? [duplicate]

This question already has answers here:
How do I pass the this context to a function?
(5 answers)
Closed 8 years ago.
how to pass "this" to another function ???
function demo1()
{
demo2(this);
}
how to get this object of demo1 into demo2 ???
function demo2()
{
//how to get this object of demo1 into demo2 ???
}
You can do this a number of ways.
Pass it in
You're already doing this, sort of.
function demo1()
{
demo2(this);
}
function demo2(demo1)
{
console.log(demo1);
}
Call it in the current scope
function demo1()
{
// Executes demo2 in scope of demo1
demo2.call(this);
}
function demo2()
{
console.log(this);
}
function demo1()
{
demo2(this);
}
function demo2(data)
{
console.log(data);
}
Check out the details on console.
That's quite easy to do. You can use .call or .apply:
demo2.call(this);
The first argument you provide will be the context (this) used during execution.

The 'this' keyword in a function [duplicate]

This question already has answers here:
How does "this" keyword work within a function?
(7 answers)
Closed 8 years ago.
I have a function in JavaScript:
function main() {
console.log(this);
}
How come this logs Document? Surely it should log function main?
If not, then how do I declare a variable within main to be accessed by the rest of the code as main.varName?
Thank you!
Hey you can do something like this.
But then this would look something like a class object.
<script>
function main() {
this.testVar = "124";
}
var testMain = new main();
alert(testMain.testVar);
</script>
The alternative is that you just create a normal global variable.
The way i am taking the code is a more class object way.
Hope i could help :)
The this keyword references the context of the function, not the function itself.
When you call a function as a method of an object, then this references the object, otherwise the context is the global context (document).
Example:
var o = {
name: 'myObject',
fn: function(){ alert(this.name); }
};
o.fn(); // alerts "myObject"
As a function is also an object, you can add properties to it:
function main() {
}
main.varName = 42;
alert(main.varName); // shows "42"
However, this is not a regular use of functions and objects. Normally main would be a plain object rather than a function if you want to access main.varName.
Also, check out the module pattern
var person = function(){
return module = {
setName: function(name){
module.name=name;
}
}
};
var bill = person();
bill.setName('bill');
console.log(bill.name);

This keyword doesn't seem to work like it should [duplicate]

This question already has answers here:
How to access the correct `this` inside a callback
(13 answers)
Closed 1 year ago.
Normally I'd assign an alternative "self" reference when referring to "this" within setInterval. Is it possible to accomplish something similar within the context of a prototype method? The following code errors.
function Foo() {}
Foo.prototype = {
bar: function () {
this.baz();
},
baz: function () {
this.draw();
requestAnimFrame(this.baz);
}
};
Unlike in a language like Python, a Javascript method forgets it is a method after you extract it and pass it somewhere else. You can either
Wrap the method call inside an anonymous function
This way, accessing the baz property and calling it happen at the same time, which is necessary for the this to be set correctly inside the method call.
You will need to save the this from the outer function in a helper variable, since the inner function will refer to a different this object.
var that = this;
setInterval(function(){
return that.baz();
}, 1000);
Wrap the method call inside a fat arrow function
In Javascript implementations that implement the arrow functions feature, it is possible to write the above solution in a more concise manner by using the fat arrow syntax:
setInterval( () => this.baz(), 1000 );
Fat arrow anonymous functions preserve the this from the surrounding function so there is no need to use the var that = this trick. To see if you can use this feature, consult a compatibility table like this one.
Use a binding function
A final alternative is to use a function such as Function.prototype.bind or an equivalent from your favorite Javascript library.
setInterval( this.baz.bind(this), 1000 );
//dojo toolkit example:
setInterval( dojo.hitch(this, 'baz'), 100);
i made a proxy class :)
function callback_proxy(obj, obj_method_name)
{
instance_id = callback_proxy.instance_id++;
callback_proxy.instances[instance_id] = obj;
return eval('fn = function() { callback_proxy.instances['+instance_id+'].'+obj_method_name+'(); }');
}
callback_proxy.instance_id = 0;
callback_proxy.instances = new Array();
function Timer(left_time)
{
this.left_time = left_time; //second
this.timer_id;
this.update = function()
{
this.left_time -= 1;
if( this.left_time<=0 )
{
alert('fin!');
clearInterval(this.timer_id);
return;
}
}
this.timer_id = setInterval(callback_proxy(this, 'update'), 1000);
}
new Timer(10);

Categories

Resources