-1

In the console tab of chrome developer tools, I typed this, and it has shown Window object. How this becomes window object here?

console.log(this);

Consider below snippet

var firstname = "Javascript";
var lastname = "Lover - SKT";

function getName() {
  this.firstname = "Sivakumar";
  this.lastname = "Tadisetti";
}

console.log(firstname);
getName();
console.log(this.lastname); // How this.lastname is working here?

I've read the following StackOverflow answers

what does this mean

this in javascript

But didn't understand how the above snippet is working (The line I commented)

Update:

I have tried above code snippet in jsfiddle where it outputs this.firstname is undefined. So that's the reason I am asking this question. But in the stackoverflow code snippet it is working fine

Sivakumar Tadisetti
  • 4,033
  • 5
  • 23
  • 51
  • 3
    @IslamElshobokshy it does, at least for me – Luca Kiebel Sep 10 '18 at 13:19
  • 1
    I don't understand the problem. What makes you think it shouldn't work? – Lightness Races in Orbit Sep 10 '18 at 13:20
  • 1
    What do you not understand here? `this` is the `window`, and after calling `getNames()`, you are changing `window.firstname` and `window.lastname`. so in the second log, they are modified – Luca Kiebel Sep 10 '18 at 13:20
  • the global scope is the window object. All global variables belong to the window object.`lastname` is declared as global variable and it can be used as `window.lastname` – Nisarg Sep 10 '18 at 13:21
  • Not OP, but I think the confusion is in why `firstname` *isn't* "Sivakumar". Looks like a misunderstanding of the difference between globally scoped local variables and window object properties. Both of these are accessible in the same way, so I can see why OP might be confused. – Joseph Marikle Sep 10 '18 at 13:23
  • Possible duplicate of [JavaScript this refers to window instead of object inside function](https://stackoverflow.com/questions/15831509/javascript-this-refers-to-window-instead-of-object-inside-function) – Sam Hanley Sep 10 '18 at 13:23
  • Possible duplicate of [How does the “this” keyword work?](https://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work) – Sam Hanley Sep 10 '18 at 13:25
  • 1
    @IslamElshobokshy A girl has no profile picture – Lightness Races in Orbit Sep 10 '18 at 13:25

5 Answers5

6

In your function, this is the same as window (or whatever the global context is in your runtime). If it was a Class method, this would be the Class instance.

You can change this by using bind, or specifying it using apply and call.

Global Function Example

var that = {}

function getTest() {
  console.log(this === window ? "this is window" : "this is not window") 
}

getTest()
getTest.call(that)
getTest.apply(that)
getTest.bind(that)()

Lambda Example

If you use lambda syntax, this is bound to this at time of calling and cannot be changed.

let that = {}

let fn = () => {
  console.log(this === window ? "this is window" : "this is not window")
}

// this is always window.  You CANNOT this on a lambda.
fn()
fn.call(that)
fn.apply(that)
fn.bind(that)()

Class Example

class Foo {
  fn() {
    console.log(this === window ? "this is window" : "this is not window")
  }
  
  // Static methods do not have a `this`, but it can be defined by call and apply, but not bind.
  static fnStatic() {
      console.log(this === window ? "this is window" : "this is not window")
  }
}

// this is Class instance, NOT window
new Foo().fn()
// Change this from class instance to window
new Foo().fn.call(window)
new Foo().fn.apply(window)
new Foo().fn.bind(window)()

// this is undefined in a static method, unless you apply or call.  YOU CANNOT BIND a static method
Foo.fnStatic()
Foo.fnStatic.call(window)
Foo.fnStatic.apply(window)
// YOU CANNOT BIND 
Foo.fnStatic.bind()(window)
Steven Spungin
  • 17,551
  • 4
  • 57
  • 56
2

In global scope, this is actually points to window object. By invoking getName you are doing the same as if:

window.firstname = "Sivakumar";
window.lastname = "Tadisetti";
streletss
  • 4,305
  • 4
  • 14
  • 34
0

In the global execution context (outside of any function), this refers to the global object whether in strict mode or not.

and console.log(this.lastname); is in global scope so here this refers to window object.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this

samee
  • 427
  • 2
  • 9
0

According to MDN

In most cases, the value of this is determined by how a function is called. It can't be set by assignment during execution, and it may be different each time the function is called.

In your case, commented this is called by the JavaScript's execution context, the context that called your program to be executed. Inside that context variable lastname lives and this means that it is a part of this object. You are calling it after your getTest function that changed the value of lastname variable and that is why you see in in console.log() with it's changed value.

Lazar Nikolic
  • 2,798
  • 1
  • 14
  • 29
0

If you're in a global context then this refers to the window object.

console.log(this);

this can refer to the window object in a function if the context stays the same

const funcArrow = () => {console.log(this)}
const func = function(){console.log(this)};
//this has no difference
const func2 = function(){console.log(this)}.bind(this);
funcArrow(); func();

The context changes if you create an instance.

var Car = function(){
  this.name = "bmw";
  console.log(this);
};

class Person {
  constructor(){
    this.name = "john";
    console.log(this);
  }
}

new Car(); new Person();

To keep the window context in an instance bind it.

class Person {
  constructor(){
    this.name = "john";
  }
  
  logWindow(){
    const someFunc = function(){console.log(this)}.bind(window);
    someFunc();
  };
}

(new Person()).logWindow();
kemicofa ghost
  • 14,587
  • 5
  • 63
  • 112