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'm just playing around and trying to figure out how the this object works and how do I pass scopes context with the bind function.
So far I got to this point (check code below), and found out that I can use bind with an object function in order to pass the scope of myObject to the object function run.
first question:
why do I need to use this.first() instead of first()?
Because otherwise its still using second's context.
myObject = {
first: function(){ console.log("myObject's first()")},
second: function(){
function first(){ console.log("second's first()")};
let run = function(){ this.first()}.bind(this);
run();
},
}
myObject.second()
Next, I wanted to take it to the next level and I nested another function within second (check code).
Second question:
From the code below i get the error Error: this.first is not a
function, and whether i invoke .bind(this) or not it gives the
same error, any clue why does this happen?
myObject = {
first: function(){ console.log("myObject's first()")},
second: function(){
function first(){ console.log("second's first()")};
function secondx2(){
function first(){ console.log("secondx2's first()")};
let run = function(){ this.first()}
run();
}
secondx2();
},
}
myObject.second()
Consider using arrows or try to store this in a global variable to access your functions
myObject = {
first: function(){ console.log("myObject's first()")},
second: function(){
var scope = this;
function first(){ console.log("second's first()")};
function secondx2(){
function first(){ console.log("secondx2's first()")};
let run1 = function(){ scope.first()} //myObject's first()
let run2 = function(){ first()}//secondx2's first()
run1();
run2();
}
secondx2();
},
}
myObject.second()
Related
This question already has answers here:
How does the "this" keyword work, and when should it be used?
(22 answers)
How to access the correct `this` inside a callback
(13 answers)
Closed 5 years ago.
class Foo {
constructor() {
this.foobar = "foobar";
}
bar() {
let _this = this;
return function() {
try {
alert("Attempt 1: "+foobar);//ReferenceError: foobar is not defined
myMethod();
} catch(err) {console.log(err);}
try {
alert("Attempt 2: "+this.foobar);//TypeError: this is undefined
this.myMethod();
} catch(err) {console.log(err);}
try{
alert("Attempt 3: "+_this.foobar);//Works!
_this.myMethod();
} catch(err) {console.log(err);}
}();
}
myMethod() {
alert("myMethod()");
}
}
new Foo().bar();
The above example is very simplified - the anonymous function inside bar() was a jQuery call originally, but for the sake of the question I didn't include that.
Why don't attempts 1 and 2 work? Do I have to use the _this trick to reference class variables/methods? How do I reference class variables/methods from nested functions?
Are you familiar with how the this keyword works in JavaScript? It's value will depend on how the function is called, not in how it is defined. For example, if you do the following:
var dog = {
greeting:"woof",
talk:function (){
console.log(this.greeting);
}
};
var cat={
greeting:"meow",
talk:dog.talk
};
dog.talk();
cat.talk();
You will see that when the talk function is called as a method of an object, that object will be used as the value of this.
The same happens with ES6 classes, where class methods are still JavaScript functions and the rules for deciding the value of this still apply. If you want to avoid declaring an auxiliar variable, you should look into using bind:
var mammal = {
greeting:"<noise>",
getTalk:function (){
return function(){
console.log(this.greeting);
};
},
getTalkBinded:function (){
return (function(){
console.log(this.greeting)
}).bind(this);
}
};
var dog={
greeting:"woof",
talk:mammal.getTalk(),
talkBinded:mammal.getTalkBinded()
};
var cat={
greeting:"meow",
talk:mammal.getTalk(),
talkBinded:mammal.getTalkBinded()
};
dog.talk();
cat.talk();
dog.talkBinded();
cat.talkBinded();
You are returning self-execution function execution result and during that function execution this it global context(not your class object). to make it work use () => {}() arrow function call syntax, as it captures current context, or function() { }.bind(this)().
See this simple example,
function a(){
this.someProp = 5;
console.log(this);
var _this = this; //so we explicitly store the value of `this` to use in a nested function
return function(){
//value of `this` will change inside this function
this.anotherProp = 6;
console.log(this);
//to use the methods and props of original function use `_this`
console.log(_this)
}
}
var c = a.call({}) //prints {someProp: 5}
c.call({}) //prints {anotherProps: 6} {someProp: 5}
This question already has an answer here:
passing this.method in setTimeout doesn't work?
(1 answer)
Closed 7 years ago.
I wrote a object constructor function with two methods, one of them calls the other via setInterval(functionName, interval), and the called function fails to get the objects properties.
I wrote a simple example on codepen: http://codepen.io/AttilaVM/pen/ZQPVEy
function Test(value) {
this.value = value
this.action = function testAction() {
console.log(this.value); // gives undefined!
}
this.play = function testPlay() {
setInterval(this.action, 500);
}
}
var test = new Test(20);
test.play();
If the method is called without setInterval it works as expected. Why is it different? How can the called method access the object's properties?
this refers to window as it is being call in setInterval(window.setInterval)
To pass the current context, Use .bind(this), The bind() method creates a new function that, when called, has its this keyword set to the provided value
function Test(value) {
this.value = value
this.action = function testAction() {
console.log(this.value);
}
this.play = function testPlay() {
setInterval(this.action.bind(this), 500);
}
}
var test = new Test(20);
test.play();
This question already has answers here:
JavaScript setInterval and `this` solution
(9 answers)
Referencing "this" inside setInterval/setTimeout within object prototype methods [duplicate]
(2 answers)
How to access the correct `this` inside a callback
(13 answers)
Closed 5 months ago.
I have a problem in regard to setInterval that I can't figure out.
There is the problem with the scope when calling setInterval or timeout from within an object, but still I can't wrap my head around it.
I tried to put my stuff inside an anonymous function, it won't work.
This is basicly my problem, simplified to the bare bones:
function Scenario(){
var ships = [];
this.ini = function(){
for (var i = 0; i < ships.length; i++){
timeoutID1 = setTimeout(ships[i].ding, 1000);
timeoutID2 = setTimeout(ships[i].bing, 1000);
}
}
this.setShips = function(){
var ship = new Ship("ship");
ships.push(ship);
}
function Ship(name){
this.name = name;
this.ding = function(){
intervalID1 = setInterval(function(){
console.log("ding");
}, 500)
}
this.bing = function(){
var _this = this;
intervalID2 = setInterval(function(){
console.log(_this.name);
}, 500)
}
}
this.setShips();
}
var scenario = new Scenario();
scenario.ini();
http://jsfiddle.net/ancientsion/xkwsn7xd/
Basicly, console.log("ding") works, console.log(_this.name) doesn't.
Why?
This is your problem simplified to bare bones:
var ship = {
name: 'Sheep',
ding: function() {
console.log(this.name);
}
}
setTimeout(ship.ding, 1000); // doesn't work correctly
It may help to see another example to understand why the above doesn't work:
var ding = ship.ding;
ding(); // doesn't work either
In JavaScript this depends on how you call your function. ship.ding() will set this to the sheep object. Bare ding() call will set this to the window object.
You can bind the function to the object you want by using .bind() method. (Function.prototype.bind())
var ding = ship.ding.bind(ship);
ding(); // works
ding is now permanently bound to the sheep object. You can use exactly the same approach with setTimeout:
setTimeout(ship.ding.bind(ship), 1000);
By the time setTimeout() gets around to call your method, it only sees the function and not the invocation context (i.e. the object to bind it to); much like this:
var bing = ships[i].bing;
bing(); // inside bing(), this == window
Basically, you need to provide setTimeout() with a prewired method invocation:
var bound_bing = ships[i].bing.bind(ships[i]);
timeoutID2 = setTimeout(bound_bing, 1000);
The "magic" happens with .bind() as it returns a new function that will have this set up properly.
You should define the value _this in Ship function:
function Ship(name){
this.name = name;
this.ding = function(){
intervalID1 = setInterval(function(){
console.log("ding");
}, 500)
}
var _this = this;
this.bing = function(){
intervalID2 = setInterval(function(){
console.log(_this.name);
}, 500)
}
}
Hoist _this out of the bing function.
you should have
_this = this,
this.bing = function() {
intervalID2 = setInterval(function(){
console.log(_this.name);
}, 500)
}
Javascript is imperative so you need to follow the execution path carefully. In function Ship, this points to a Ship object, in function bing, this points to the global scope (window). You need to save a reference to this so that you can refer back to it in these types of functions.
You put ships[i].bing in setTimeout turns out that the caller of bing is not ships[i] but global, so _this is pointing to global actually.
This question already has answers here:
How to access the correct `this` inside a callback
(13 answers)
Closed 8 years ago.
In one of my classes, a method performs AJAX requests. In the callback function of a request, I need to call another method of my object, using this. But this does not refer to my object in this context, so I don't know how to do... Is it only possible ?
To clarify, please consider the following code :
function MyClass(arg) {
this.foo = arg;
}
MyClass.prototype = {
myMethod: function() {
console.log("I am myMethod");
},
myGet: function (){
$.get("http://example.iana.org/",function(data){
this.myMethod(); // does not work, because 'this' does not refer to my object
});
}
}
var obj = new MyClass("Javascript is complicated");
obj.myGet();
You can define a variable to store this in the closure :
myGet: function (){
var _this = this;
$.get("http://example.iana.org/",function(data){
_this.myMethod();
});
}
or use $.proxy :
myGet: function (){
$.get("http://example.iana.org/", $.proxy(function(data){
this.myMethod();
}, this));
}
or, if you don't do more than calling myMethod in the callback :
myGet: function (){
$.get("http://example.iana.org/", $.proxy(this.myMethod, this));
}
In modern browsers you can also use bind. When I don't have to be compatible with IE8 I do
myGet: function (){
$.get("http://example.iana.org/", this.myMethod.bind(this));
}
http://jsfiddle.net/ZLH7J/1/
What the jsFiddle and code below shows are two examples that essentially do the same thing. When trying to call first(); or this.first(); in either example, an undefined error is thrown. I can call the functions later through the instance, but not when trying to instantiate the object using init(){...}() like a constructor. I put init() at the bottom thinking it was an order of operations thing, but that is not the case. This does not work the way I thought it would work.
I am curious to understand how this is supposed to be done, and why this cannot be done.
//create and return an obj
var fishSticks = function(){
return {
first: function(){
document.getElementById('output').innerHTML="Success";
},
init: function(){
try{
first(); //err
this.first(); // also err
}catch(e){
document.getElementById('output').innerHTML=e.toString();
}
}()
}
}
//do function stuff and then return 'this'
var fishFillet = function(){
var first = function(){
document.getElementById('output2').innerHTML="Success";
}
var init = function(){
try{
first(); //err
this.first(); // also err
}catch(e){
document.getElementById('output2').innerHTML=e.toString();
}
}()
return this;
}
var test = new fishSticks();
var test2 = new fishFillet();
You need to understand two things:
1) JavaScript does not automatically insert this like Java does, so the first() call will only look through the lexical scope for a definition of first, it will nok look at the this object. Therefore the call to first() should work but this will be bound to something else than what you might expect inside first.
2) Local variables in a constructor do not become members of the constructed object.
In your second example, if you comment out the call in "init" to this.first() then you get the "Success" message.
The first version doesn't work because JavaScript simply does not allow for references to be made within an under-construction object to the object itself. There's just no way to do it.
The second one works (well the simple reference to "first" works) because "first" is declared as a local variable. Local variables are not properties of any object, and in particular they're not properties of the object allocated when the function is called with new. That's why this.first() doesn't work.
In the second one, you could make this.first() work by declaring things differently:
var fishFillet = function(){
this.first = function(){
document.getElementById('output2').innerHTML="Success";
}
var init = function(){
try{
this.first(); //will work
}catch(e){
document.getElementById('output2').innerHTML=e.toString();
}
}()
return this;
}
Also, for what it's worth, the weird anti-pattern of
var something = function() { ... }
is not as useful as
function something() { ... }
There's no reason to use the var declaration instead of the function declaration.
How about...
var fishFillet = function () {
var first = function () {
document.write( 'Success' );
};
var init = function () {
first();
};
init();
return {
first: first
};
};
And then:
var ff = fishFillet(); // calls init() which calls first()
ff.first(); // call first() manually
Live demo: http://jsfiddle.net/uaCnv/
So, first you define all your functions, next you manually invoke init, and last you return an object containing those functions which should be available through the resulting object (as methods).
Since you are using both as a constructor, format them as such:
function fishFillet(){
this.first = function(){
document.getElementById('output2').innerHTML="Success";
}
this.init = function(){
try{
this.first();
}catch(e){
document.getElementById('output2').innerHTML=e.toString();
}
}
}
var food = new fishFillet();
food.init();
The reason it wasn't working for you is b/c "first" is created as a local varaible, and is deleted after execultion. Init isn't being called until after the execution of the constructor has finished