weird part 37 — ‘this’ keyword point to window or object?
1 min readOct 12, 2018
#window — global object
function a (){
console.log(this)//window - global variable
this.newVariable = 'hello'
}var b = function(){
console.log(this)
}a();//window
console.log(newVariable)
b(); //window
#object
var c = {
name:'C object',
log:function(){
console.log(this)
}
}
c.log(); //'this' is object{name: "C object", log: ƒ}
# common error
var c = {
name:'C object',
log:function(){
this.name = 'updated c objet name'
console.log('this 1',this)
var setname = function(newname){
this.name = newname; // pointing to window
}
setname('updated again! overwrite c object ')
console.log('this 2',this) // window.name
}
}
console.log(c.name)
c.log(); //{name: "C object", log: ƒ}
- internal function ‘setname’ is pointing to window
# how this keyword can point to this c object? — var self = this
var c2 = {
name:'C2 object',
log:function(){
var self = this; //mutate
self.name = 'updated c2 objet name'
console.log('this 1',this)
var setname = function(newname){
self.name = newname;
}
setname('updated again! c2 object ')
console.log('self',self) //{name: "updated again! c2 object ", log: ƒ}
console.log('this',this) //{name: "updated again! c2 object ", log: ƒ}
}
}
console.log(c2)
c2.log();
- var self = this — pointing the whole object ‘C’