原生JS基础知识(十六)

原生JS基础知识

我的github

try…catch

  • try{}catch(e){}finally{}

    try {
      console.log('a');
      console.log(b);
      console.log('c');
    } catch (e) {
      console.log(e);
      console.log(e.name);
      console.log(e.message);
    }
    console.log('d');
    
  • Error.name( e.name )的六种值对应的信息

    • EvalError : eval()的使用与定义不一致

    • RangeError : 数值越界

    • ReferenceError : 非法或不能识别的引用数值

    • SyntaxError : 发生语法解析错误

    • TypeError : 操作数类型错误

    • URIError : URL处理函数使用不当

es5严格模式

  • “use strict”

    • 不再兼容es3的一些不规则语法 , 使用全新es5规范

      扫描二维码关注公众号,回复: 10144325 查看本文章
    • 就是一行字符串 , 不会对不兼容严格模式的浏览器产生影响

  • 两种用法

    • 全局严格模式

    • 局部函数内严格模式 ( 推荐 )


es5严格模式不支持的写法和一些注意事项如下

  • 不支持arguments.callee、func.caller ( 参见13.md )

  • 不支持with()的使用 , 因为修改作用域链效率低

    // with 用法示例 ( 可应用于js命名空间 , 参见12.md )
    var obj = {
      name: 'with'
    }
    var name = 'GO';
    function foo() {
      var name = 'AO';
      with(obj) {
        // 优先级 : obj > AO > GO , 故打印with
        console.log(name);
      }
    }
    
  • 变量赋值前必须被声明 , 否则报错

    'use strict'
    aaa = 123; // Uncaught ReferenceError: aaa is not defined
    
  • 局部this必须被赋值 , 否则undefined

    'use strict';
    function Foo() {
      console.log(this); // undefined
    }
    Foo();
    
  • 局部this被赋值什么就是什么

    // es3.0
    function Foo() {
      console.log(this); // Number {123}
    }
    Foo.call(123);
    
    // es5.0
    'use strict'
    function Foo() {
      console.log(this); // 123
    }
    Foo.call(123);
    
  • 拒绝重复参数和属性

    • Tips : 重复参数会报错, 重复属性不报错

      'use strict'
      var obj = { name: 'liu', name: 'li' } // 不报错但写法不被允许
      function foo(name, name) {
        // Uncaught SyntaxError: Duplicate parameter name not allowed in this contextsole.log(name);
      }
      foo(1, 2);
      
  • 不支持eval() , 因为eval()可以改变作用域

    // eval()的基础用法 : 可以将字符串参数当作代码执行
    var foo = '123';
    eval('console.log(foo)'); // 123
    
发布了49 篇原创文章 · 获赞 29 · 访问量 1907

猜你喜欢

转载自blog.csdn.net/Brannua/article/details/104445123