什么是“严格模式”它是如何使用的? [英] what is "strict mode" and how is it used?

查看:1289
本文介绍了什么是“严格模式”它是如何使用的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在浏览Mozilla开发者网络上的JavaScript参考,我发现了一个名为strict mode的东西。我读了它,我很难理解它的作用。有人可以简单解释(一般)它的目的是什么以及它有用吗?

I've been looking over the JavaScript reference on the Mozilla Developer Network, and I came across something called "strict mode". I read it over and I'm having trouble understanding what it does. Can someone briefly explain (in general) what its purpose is and how it is useful?

推荐答案

它的主要目的是做更多检查。

Its main purpose is to do more checking.

只需在代码顶部添加use strict; ,然后再进行其他操作。

Just add "use strict"; at the top of your code, before anything else.

例如, blah = 33; 是有效的JavaScript。这意味着你创建一个完全全局变量 blah

For example, blah = 33; is valid JavaScript. It means you create a completely global variable blah.

但是在严格模式下它是一个错误,因为你没有使用一些关键字var用于声明变量。

But in strict mode its an error because you did not use the keyword "var" to declare the variable.

大部分时间你并不是要在某些中间创建全局变量任意范围,因此大多数时候写入 blah = 33 这是一个错误,程序员实际上并不希望它是一个全局变量,他们打算写 var blah = 33

Most of the time you don't mean to create global variables in the middle of some arbitrary scope, so most of the time that blah = 33 is written it is an error and the programmer didn't actually want it to be a global variable, they meant to write var blah = 33.

它同样不允许做很多技术上有效的事情。 NaN =lol不会产生错误。它也不会改变NaN的值。 using strict(和类似的奇怪语句)会产生错误。大多数人都很欣赏这一点,因为没有理由写 NaN =lol,所以最有可能是拼写错误。

It similarly disallows a lot of things that are technically valid to do. NaN = "lol" does not produce an error. It also doesn't change the value of NaN. using strict this (and similar weird statements) produce errors. Most people appreciate this because there is no reason to ever write NaN = "lol", so there was most likely a typo.

在严格模式的MDN页面上阅读更多信息

这篇关于什么是“严格模式”它是如何使用的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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