如何在Chrome的“JavaScript控制台”中使用“严格”模式 [英] How to use 'strict' mode in Chrome 'JavaScript Console'

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

问题描述

我在Chrome的JavaScript控制台(版本:35.0)上练习JavaScript,并且无法按预期使用'use strict'子句。

以下代码片段:

  var obj = {x:1,y:2} 

//用'可写'标志定义新属性为false。
Object.defineProperty(obj,z,{value:3,writable:false,enumerable:false,configurable:false})

//尝试更改属性'z' ,
使用严格;输出:4

>

根据我的理解,在非严格模式下更改'non-writable'属性的值将会失败,并严格抛出'TypeError'模式,但我没有看到异常。

  console.log(obj)


对象{x:1,y:2,z:3}


$ b

尽管属性值没有改变,但我预计会发生异常。
请改正,如果我做错了什么?

解决方案

使用严格模式的最简单方法是使用一个IIFE (即时调用函数表达式)如下所示:

$ p $ code $($(
$ $ b $'use strict' ;
var foo = 123; //正常工作
bar = 345; // ReferenceError:bar未定义
}());

要在控制台中创建新行,请使用 shift + enter ,或者先在独立的编辑器中编写代码,然后将其复制粘贴到控制台。设置一个小提琴是一切都很好,但只需用它写的标记来测试你的代码(即:清除浏览器缓存和测试)。

但是,我会敦促你安装node.js,仍然。使用JSHint测试代码或验证它(语法和编码风格明智)要容易得多。还有很多方法可以检查和使用node.js的代码,所以它是一个很好的开发工具。


I am practicing JavaScript on Chrome's 'JavaScript Console' ( version: 35.0) and I am unable to use the 'use strict' clause as expected.

For the following code snippet :

var obj={x:1,y:2}

//Define new property with 'writable' flag as false.
Object.defineProperty(obj, "z", {value:3, writable:false, enumerable:false, configurable:false})

// Try to change the property 'z',
"use strict"; obj["z"]=4

Output: 4

As per my understanding, changing value of a 'non-writable' property will silently fail in non-strict mode and throw 'TypeError' in strict mode, But I don't see the exception.

console.log(obj)

Object {x: 1, y: 2, z: 3}

Even though the property value is not changed but I am expecting a exception. Please correct if I am doing something wrong ?

解决方案

The easiest way to use strict mode is to use an IIFE (immediately Invoked Function Expression) like so:

(function()
{
    'use strict';
    var foo = 123;//works fine
    bar = 345;//ReferenceError: bar is not defined
}());

To create a new-line in the console, use shift + enter, or write your code in a separate editor first, then copy-paste it to the console. Setting up a fiddle is all fine and dandy, but just test your code with the markup it was written for (ie: just clear the browser cache and test).
However, I'd urge you to install node.js, still. It's a lot easier to test your code, or validate it (both syntactically and coding-style wise) using JSHint. There are also a lot of ways to examine and your code that run out of node.js, so it's a really good development tool to have

这篇关于如何在Chrome的“JavaScript控制台”中使用“严格”模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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