No output from the object functions [duplicate] - javascript

This question already has answers here:
Referencing "this" inside setInterval/setTimeout within object prototype methods [duplicate]
(2 answers)
How to return value from an asynchronous callback function? [duplicate]
(3 answers)
Closed 5 years ago.
This question is from an written test for a company. It looks very confusing. I thought it will print whatever this.name is set to. Bu when I typed the code it shows nothing. I have little knowledge about closures and I think it is related to the problem. I want a little explanation here.
function dd(name) {
this.name = name;
this.go = function() {
setInterval(function() {
return this.name;
}, 2000)
}
}
var tt = new dd("corolla");
tt.go()

You can't get the return value from setInterval in this way. Try with a callback as in the following snippet
function dd(name)
{
this.name=name;
console.log( name );
var _this = this;
this.go=function(cb)
{
setInterval(function() {
cb(_this.name);
},1000)
}
}
var tt=new dd("corolla");
tt.go(function(ret) {
console.log( ret );
})
Also, please note that inside setInteval the value of this is not the same as in the otter function. That's why var _this=this;

Related

Why adding new method with prototype doesn't work as intended [duplicate]

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)
Pass correct "this" context to setTimeout callback?
(6 answers)
Closed 4 years ago.
So i am self learning developer. I learned quite a lot of php and started doing javascript. I was introduced to javascript first class functions and all that. I learned that you can add new property (var or function) into class by prototype which is from my understanding object that has every other object (like variable, function). While trying prototype out i got problem with this code:
function Fox(color) {
this.color = color;
}
Fox.prototype.speak = function() {
console.log('I am ' + this.color);
};
var myFox = new Fox('blue');
window.setTimeout(myFox.speak, 1000);
this.color is undefined in this case and i am having hard time understanding why. It works like this but with no time delay. I think setTimeout not working properly is because of how it is made to work, to have function(first class) as argument not to execute function ( as it does if you put () ). Again don't know why this returns value blue.
/* This works but with no time delay: */
window.setTimeout(myFox.speak(), 1000);
/* returns blue */
Your problem - if first case: you lost context
Try it:
function Fox(color) {
this.color = color;
}
Fox.prototype.speak = function() {
console.log('I am ' + this.color);
};
var myFox = new Fox('blue');
setTimeout(myFox.speak.bind(myFox), 1000);
also you can use callback with your method:
function Fox(color) {
this.color = color;
}
Fox.prototype.speak = function() {
console.log('I am ' + this.color);
};
var myFox = new Fox('blue');
setTimeout(function(){myFox.speak()}, 1000);

Double function name in javascript [duplicate]

This question already has answers here:
Why use named function expressions?
(5 answers)
Closed 4 years ago.
Here is the code sample I have a question about:
var javascriptObject = {
functionName1: function functionName2() {
}
}
I understand the concept of an object in the javascript. I understand everything in the code sample except the functionName2 what is its purpose?
And I saw the code in the real life projects:
init: function init() {
init._base.call(this);
}
The code above does not work if I get rid from the second init. What does that second function name mean in javascript?
Object in JS are just name value pairs nothing more
var javascriptObject = {
functionName1: function functionName2() {
}
}
So what your doing is having a object which has a name of functionName1 which has the value of
function functionName2() {}
The name of the function stored in this value is functionName2 but this also could be omitted since it is not necessary to invoke the function.
For example you could run the function without the functionName2
var javascriptObject = {
functionName1: function () {
return 5;
}
};
var bar = javascriptObject.functionName1();
console.log(bar);

this context lost when passing a reference to a method [duplicate]

This question already has answers here:
Pass correct "this" context to setTimeout callback?
(6 answers)
Closed 6 years ago.
In this example
class Car {
describe() {
console.log("I have " + this.wheels);
}
testMe() {
setTimeout( this.describe, 1000);
}
constructor(wheels) {
this.wheels = wheels;
}
}
let myCar = new Car(4);
myCar.testMe(); // I have undefined
How come the expected value of this isn't passed inside the describe function ?
edit : Can you confirm that is setTimeout was an arrow function, I wouldn't get undefined ?
A bare function reference has no context, even if it was retrieved as a property of an object.
Within your testMe function you need either:
setTimeout(() => this.describe(), 1000);
or
setTimeout(this.describe.bind(this), 1000);
or
let self = this;
setTimeout(function() {
self.describe();
}, 1000);
That last one could be written as an arrow function, of course, but if you're doing that you might as well use the first version, with no local copy of this required.
Regarding your edit, it is possible to pass just this.describe by making describe an arrow function, assigned from inside the constructor, but note that this then means that every instance of the object would have its own copy of that function instead of there just being a single copy on the prototype of the class:
constructor(wheels) {
this.wheels = wheels;
this.describe = () => {
console.log("I have " + this.wheels);
}
}

Method called by other method with setInterval can not access object property in js [duplicate]

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();

More elegant way to call method from ajax callback function [duplicate]

This question already has answers here:
How to access the correct `this` inside a callback
(13 answers)
Closed 8 years ago.
I have a problem with javascript namespaces.
I want to call secondMethod from ajax callback function but I don't know how to get reference to it.
I have done it like that yet. But variable thisReference seems to me awkward. And whole construction is difficult to read.
So I'm writing there for help and answer how to rewrite it better.
var testObject = new TestObject();
testObject.firstMethod("hello world!");
function TestObject() {
var thisReference = this;
this.firstMethod = function(firstParam) {
ajaxFunc(firstParam, function(ajaxResult) {
thisReference.secondMethod(ajaxResult);
});
};
this.secondMethod = function(secondParam) {
alert("secondMethod " + secondParam);
};
}
function ajaxFunc(hello, callBack) {
callBack(hello);
}
Thanks a lot.
Ondra
Something like what you're doing is a common way to do it. Using:
var that = this;
or:
var self = this;
are common names to keep a hold of your original scope.
Another option (which I prefer) is to bind the this object to the method you're calling so that you have access to it in the callback. That would look like this:
this.firstMethod = function(firstParam) {
ajaxFunc(firstParam, function(ajaxResult) {
this.secondMethod(ajaxResult);
}.bind(this));
};
Hope that helps.

Categories