⏱ 0:00est. 6 min
Chapter 37- Objects, Functions and 'this'
Notes
//this
Example 1
console.log(this);// this is immediately available even at the global execution context, window object (global object)
Example 2
function a(){
console.log(this); //window object
//we can attach new variable to the window object
this.newVariable = ‘hello';
}
a();
console.log(newVariable);
Explanation - when you create a function the this keyword is still going to point the global object
Similarly
Example 3 //var b gets a functional express by creating anonymous function
var b = function a(){
console.log(this);
}
b(); //still window object
Example 4
var c = {
name : ‘The c object',
log : function(){
console.log(this); //the object in which the method is sitting inside of
}
}
c.log(); // Object {name : "The c object" ,log: function(){ console.log(this)}}
Example 5
var c = {
name : ‘The c object',
log : function(){
this.name = ‘Updated c object'; //mutate - change the object properties
console.log(this); //the object in which the method is sitting inside of
}
}
c.log(); // Object {name : "Updated c object" ,log: function(){ this.name = ‘Updated c object';console.log(this)}}
##BUG in js -
Example 6
var c = {
name : ‘The c object',
log : function(){
this.name = ‘Updated c object'; //mutate - change the object properties
console.log(this); //the object in which the method is sitting inside of
var setname = function(newname){
this.name = newname;
}
// didn't work on c but added new property to window object
setname(‘Updated again!, The c object');
console.log(this);
}
}
c.log(); // Object {name : "Updated c object" ,log: function(){ this.name = ‘Updated c object';console.log(this);var setname = function(newname){this.name = newname;} setname(‘Updated again!, The c object');console.log(this);}}
A very common pattern can b used in this case to avoid errors in code because of "this"
var c = {
name : ‘The c object',
log : function(){
var self = this; //self will be pointing at the same location in memory as this
self.name = ‘Updated c object'; //mutate - change the object properties
console.log(self); //the object in which the method is sitting inside of
var setname = function(newname){
self.name = newname; //js will look for self in scope chain
}
//will work now
setname(‘Updated again!, The c object');
console.log(self);
}
}
c.log(); //Object {name : "Updated again!, The c object" ,log: function(){ this.name = ‘Updated c object';console.log(this);var setname = function(newname){this.name = newname;} setname(‘Updated again!, The c object');console.log(this);}}