this is window inside the function of a class [duplicate] - javascript

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 1 year ago.
I have some code here.
I am aware that this reference wont be carried in anonymous functions.
But here, even when using a function of an object, the this inside that is window.
var MyClass = function (div) {
this.array = [];
};
MyClass.prototype = {
addToArray: function (elem) {
this.array.push(elem);
},
processAndAdd: function(elemArray){
elemArray.forEach(this.addToArray);
}
}
var myObj = new MyClass();
myObj.processAndAdd([1, 2, 3]);
console.log('test');
Error: Line: this.array.push(elem);
push of undefined.
On inspection, the this here is window Object
I want to know why this is window here, and how to restructure my code to properly handle this.

The reference to this object is no more MyClass constructor after you pass the callback function body as callback to forEach. Bind the function body with the current this context and your code should work.
var MyClass = function (div) {
this.array = [];
};
MyClass.prototype = {
addToArray: function (elem) {
this.array.push(elem);
},
processAndAdd: function(elemArray){
elemArray.forEach(this.addToArray.bind(this));
}
}
var myObj = new MyClass();
myObj.processAndAdd([1, 2, 3]);
console.log('test');

Related

Undefined Array in constructor with TypeError: Cannot read property '0' of undefined [duplicate]

This question already has answers here:
How to access the correct `this` inside a callback
(13 answers)
Closed 6 years ago.
My code creates a dispatcher from constructor ColorDispatcher. After window.onload, dispatcher.hoverOutHandler is regularly called after 1.5 sec. when changeBGColor called, the typeError described in the title shows; However I really cannot figure out why.
var ColorDispatcher = function() {
this.changeColorTimerID = 0;
this.rgbColorArray = new Array(0, 0, 0);
};
ColorDispatcher.prototype = {
hoverOutHandler: function() {
this.changeColorTimerID = window.setInterval(this.changeBGColor, 1500);
},
changeBGColor: function() {
//something went wrong here.
alert(this.rgbColorArray[0]);
},
};
var dispatcher = new ColorDispatcher();
window.onload = dispatcher.hoverOutHandler();
Change the following line:
this.changeColorTimerID = window.setInterval(this.changeBGColor.bind(this),1500);
setInterval called the function on the window scope therefor the array wasn't found. With .bind you can bind a function to a scope (in this case this).

Object has no method? [duplicate]

This question already has answers here:
How to access the correct `this` inside a callback
(13 answers)
Closed 8 years ago.
I tried searching for this for about an hour and can't seem to find a solution that works for me. I have a function (Function2) inside an object that is called by an interval. Function2 cannot find Function1, and is saying the method does not exist. Why might this be, or what is wrong with my syntax?
var ClassA = function ()
{
this.attribute = "";
this.function1 = function()
{
alert("Function 1");
};
this.function2 = function()
{
alert("Function 2");
this.function1(); <----- Does not exist?
};
this.function3 = function()
{
setInterval(this.function2, 5000);
};
};
var CLASS_A = new ClassA();
CLASS_A.function3();
The setInterval behaves asynchronously. When you provide this.function2 as parameter to setInterval, you're basically providing a callback method. When setInterval has reached 5000 it calls your callback method.
The "this" keyword changes depending on the context. The callback context is very different from your object's "ClassA" context. It's not the same "this".
The trick is to do this:
var ClassA = function(){
var that = this;
//And then everywhere else use that instead of this.
that.function1 = function() { ...
that.function2 = function() { ...
that.function1
that.function3 = function ....
}
Good luck.
You have to look carefully about what this means in JavaScript and in what context your function is being called. You can ensure that the context is what you intend by using the bind method of Function, as in the following edit:
var ClassA = function ()
{
this.attribute = "";
this.function1 = function()
{
alert("Function 1");
};
this.function2 = function()
{
alert("Function 2");
this.function1(); // Exists but only on the ClassA, not on Window
};
this.function3 = function()
{
setInterval(this.function2.bind(this), 5000);
};
};
var CLASS_A = new ClassA();
CLASS_A.function3();

Change value object Javascript [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 normal object in javascript, contenting functions and values.
This is my example object:
var MyObject = {
myData: 1,
a: function() {},
b: function() {}
}
Now in the function a there is some logic that fire on it, but it should change even the value of myData property.
But when i try get it from the method b, that value come as an undefined value, instead of the value changed.
I created a JsFiddle with a small example of the behaviour of the my object. I realized that it how Javascript behave, but I didn't understand why.
The issue is because this within the click handlers refers to the element which was clicked, not the object the handler functions are members of. You need to cache this:
a: function () {
var self = this;
$('.setValue').click(function() {
self.myData = 2;
});
},
b: function () {
var self = this;
$('.getValue').click(function() {
alert(self.myData);
});
}
Updated fiddle
In JavaScript, each function has its own this argument. In your case, you want to access the outer function's this variable so you should do something like this:
var that = this;
Here is the updated jsfiddle:
http://jsfiddle.net/xaaLQ/5/

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

Is it possible to instantiate empty object/object without parameters from constructor? [duplicate]

This question already has answers here:
Class vs. static method in JavaScript
(15 answers)
Closed 8 years ago.
In code:
function Foo() {
this.someMethod = function() {
console.log("property");
};
}
Is possible to instantiate empty Foo object, and call someMethod on it? Like:
Foo.someMethod();
I got TypeError, which means not.
Ok, next, can I define default method like with __construct in PHP which execute some code upon instantiation of object, or even better let make evaluation of that function be some property value inside object, so even when I instantiate "empty" object, that function set some value upon instantiation of new object.
The way you are doing it,
var fooObj = new Foo();
fooObj.someMethod();
will work fine.
You can also try doing it this way:
var Foo = (function(){
function Foo() {
// Foo constructor
}
Foo.prototype.someMethod = function(){
// public Foo function
};
var somePrivateFunction = function(){
// private Foo function
};
return Foo;
})();
var fooObj = new Foo();

Categories

Resources