Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why "this" inside of a function's returning object window

there is two type of scope in javascript named function scope global scope

now i am executing this code

function abc()
{
alert(this);
}
abc();

abc call returning me [object Window] Why?? function makes another scope so why it is representing window

like image 913
Mohammad Faizan khan Avatar asked Mar 06 '14 06:03

Mohammad Faizan khan


People also ask

Why is object object being returned?

[object Object] is a string version of an object instance. This value is returned by a JavaScript program if you try to print out an object without first formatting the object as a string.

What is this inside a function JavaScript?

The this keyword refers to the object the function belongs to, or the window object if the function belongs to no object. It's used in OOP code, to refer to the class/object the function belongs to For example: function foo() { this.

Why we use this in JavaScript?

“This” keyword refers to an object that is executing the current piece of code. It references the object that is executing the current function. If the function being referenced is a regular function, “this” references the global object.

What happens when you return an object from a function?

When an object is returned by value from a function, a temporary object is created within the function, which holds the return value. This value is further assigned to another object in the calling function.


1 Answers

this, inside any function, will be the object on which the function is invoked. In your case, you are not invoking it on any object. So, by default this refer to global object, in your browser, it is the window object.

But in strict mode, if you invoke it like this, this will be undefined.

"use strict";
function abc() {
    console.log(this);    // undefined
}
abc();

Or

function abc() {
    "use strict";
    console.log(this);   // undefined
}
abc();
like image 174
thefourtheye Avatar answered Sep 18 '22 09:09

thefourtheye