zoukankan      html  css  js  c++  java
  • strict 严格模式

    严格模式可以让你更早的发现错误,因为那些容易让程序出错的地方会被找出来
     
    打开严格模式:"use strict"
    不支持的javascript引擎会忽略它,当作是一个未赋值字符串。如果在一个脚本使用全局使用严格模式,那么在同一个页面的其他脚本也会严格。也可以在某个函数里声明使用严格模式。
     
    在平时,没有声明直接使用的变量作为全局变量处理
    number = 1;
    在严格模式里,会抛出引用错误(referenceerror)
    同时变量是无法delete的,在平时 delete number会安静地失败,在严格模式里也会报引用类型错误
     
    严格模式下,变量和函数名都无法使用implements,interface,let,package,private,protected,public,static,yield 这是保留给以后用
     
    对于对象的操作有更大的限制,对于许多平时会安静地失败操作都会报错:
    Assigning a value to a read-only property throws a TypeError.
    Using delete on a nonconfigurable property throws a TypeError.
    Attempting to add a property to a nonextensible object throws a TypeError.
     
    还有,不能声明重复属性:
    var person = {
       name: “Nicholas”,
       name: “Greg”
    };
     
    函数的行参名字必须唯一的,在平常不会报错,直接使用后面那个:
    function sum (num, num){
    //do something
    }
     
     
    在平时函数里改变传进来的参数,arguments也会跟着改变,但是严格模式不会。也就是严格模式下两者是分开独立的。
    function showValue(value){
    value = “Foo”;
    alert(value); //”Foo” alert(arguments[0]); //Non-strict mode: “Foo”//Strict mode: “Hi”
    }
    showValue(“Hi”);
     
    以下两者在严格模式都无法使用:
    arguments.callee 平时可以访问函数自己
    arguments.caller  可以访问调用本函数的caller
     
    函数声明必须是at the top level of a script or function
    if (true){
        function doSomething(){//... }
    这样是会报错的。
     
    对于eval函数,最大的限制在于不会在包含他的执行上下文内创建变量或者函数:
    function doSomething(){
    eval(“var x=10”);
    alert(x);//抛出ReferenceError
    }
     
    不在执行上下文的eval里的还是可以创建变量,但会收到限制,这些变量保存到一个特殊的作用域,代码执行完就会销毁:
    “use strict”;
    var result = eval(“var x=10, y=11; x+y”);
    alert(result); //21
    这里执行alert时,x,y已经被销毁了
     
    明确不能定义操作eval和arguments:
    - ➤  Declaration using var
    - ➤  Assignment to another value
    - ➤  Attempts to change the contained value, such as using ++
    - ➤  Used as function names
    - ➤  Used as named function arguments
    - ➤  Used as exception name in try-catch statement
     
    对this的限制,下面例子在平时this转而指向全局变量,输出red,严格模式下会出现错误,因为this只会指向null
    var color = “red”;
    function displayColor(){         alert(this.color);
    }
    displayColor.call(null);
     
    严格模式还移除了一些常用会出错的,例如with,不允许使用八进制
     
    parseInt函数的改变:
    var value = parseInt(“010”)
    非严格模式输出8,严格模式输出10
     
    在需要严格模式的代码前添加
    "use strict"
    单纯一个函数也可以
     
    function doSomething(){ “use strict”;
     
    //function body }
     
    该模式会改变许多运行方式
  • 相关阅读:
    得到内网可用的SqlServer 及某数据库下的表及其他的架构
    VS2005 XML注释生成XML文档文件
    华表 单元格公式设定与计算
    自定义控件开发示例二
    自定义控件的 Enum类和Color类 属性的公开设定
    入门者初试 Cell(华表)结合C#的应用
    VS2005 + VSS6.0 简单应用示例
    SQL2000联机丛书:使用和维护数据仓库
    VS2005 通过SMO(SQL Management Objects) 管理 数据库的作业 警报 备份 等任务
    SQL2000联机丛书:基本 MDX
  • 原文地址:https://www.cnblogs.com/chuangweili/p/5166468.html
Copyright © 2011-2022 走看看