为什么“这个”在函数的返回对象窗口中 [英] Why "this" inside of a function's returning object window

查看:139
本文介绍了为什么“这个”在函数的返回对象窗口中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

JavaScript中有两种类型的作用域,分别命名为
函数作用域
全局作用域
p

此代码

 函数abc()
{
alert(this);
}
abc();

abc call returned me [object Window]
为什么?函数使另一个作用域为什么它代表窗口

解决方案

this ,在任何函数内部,将是该函数被调用的对象。在你的情况下,你不是在任何对象上调用它。因此,默认情况下这个指的是 global 对象,在您的浏览器中,它是窗口 object。



但是在 strict 模式下,如果你像这样调用它, code>这个将会是 undefined

 严格使用; 
函数abc(){
console.log(this); //未定义
}
abc();



  function abc(){
use strict;
console.log(this); //未定义
}
abc();


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

解决方案

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

这篇关于为什么“这个”在函数的返回对象窗口中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆