Why “this” inside of a function's returning object window

一笑奈何 提交于 2019-12-20 01:41:51

问题


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


回答1:


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



回答2:


Your function is under global(window) object. I mean,

function abc()
{
    alert(this);
}
abc(); 
// or You can either call by
window.abc()

You can write your function under custom object

// Function under custom object
var customObj = {
    abc : function () {
        alert(this);
    }
};
customObj.abc()



回答3:


The this keyword refers to the object the function belongs to, or the window object if the function belongs to no object.

Reference

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



来源:https://stackoverflow.com/questions/22217279/why-this-inside-of-a-functions-returning-object-window

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!