Javascript这是未定义的。这应该是全球对象 [英] Javascript this is undefined. This should be global object

查看:83
本文介绍了Javascript这是未定义的。这应该是全球对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么在从网页加载脚本时在google dev控制台中出现以下错误?

Why do I get the following error in the google dev console when loading the script from a web page?

但是如果我使用开发工具单步调试代码调试器没有发生错误和
this.name ='Jane Doe'按预期进行?

But if I step through the code with the dev tool debugger the error does not occur and this.name = 'Jane Doe' as expected?

index.html

index.html

<script type="text/javascript" src="main.js"></script>

main.js

'use strict';
var name = 'Jane Doe',
    greet = function () {
        return 'My name is ' + this.name;
    };
console.log(greet());

console:

Uncaught TypeError:不能读取属性'name'未定义

Uncaught TypeError: Cannot read property 'name' of undefined

推荐答案

未受约束严格模式下的全局对象。

this is not bound to the global object in strict mode.

这个的值在为null时不会转换为全局对象或未定义。
JavaScript

The value of this is not converted to the global object when it is null or undefined. JavaScript

function testFunc() {
    return this;
}
var testvar = testFunc();

在非严格模式下, testvar 是全局对象,但在严格模式下,该值未定义。

In non-strict mode, the value of testvar is the global object, but in strict mode the value is undefined.

http://msdn.microsoft.com/en-us/library/br230269(v = vs.94).aspx

这解决了大部分问题。我仍然无法解释为什么它在逐步执行chrome调试器中的代码时工作。

That solves most of it. I still can't explain why it works while stepping through the code in the chrome debugger.

这篇关于Javascript这是未定义的。这应该是全球对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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