您的位置:首页 > Web前端 > JavaScript

javascript严格模式

2016-05-05 15:03 513 查看
设立"严格模式"的目的,主要有以下几个:

  1. 消除Javascript语法的一些不合理、不严谨之处,减少一些怪异行为;

  2. 消除代码运行的一些不安全之处,保证代码运行的安全;

  3. 提高编译器效率,增加运行速度;

  4. 为未来新版本的Javascript做好铺垫。

严格模式下,变量都必须先用var命令声明,然后再使用。

test_163:/home/exenode/es6 # more mytest.js
class Animal{
constructor(name){
this.name = name;
}

sayName(){
console.log('My name is ' + this.name);
}

}

class Programmer extends Animal{
constructor(name){
super(name);
}

program(){
console.log("I'm coding...");
}

}

var animal = new Animal('dummy');

wayou = new Programmer('wyou');

animal.sayName();
wayou.sayName();

wayou.program();
test_163:/home/exenode/es6 #
test_163:/home/exenode/es6 # node mytest.js
/home/exenode/es6/mytest.js:1
(function (exports, require, module, __filename, __dirname) { class Animal{
^^^^^

SyntaxError: Block-scoped declarations (let, const, function, class) not yet supported outside strict mode
at exports.runInThisContext (vm.js:53:16)
at Module._compile (module.js:414:25)
at Object.Module._extensions..js (module.js:442:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:313:12)
at Function.Module.runMain (module.js:467:10)
at startup (node.js:136:18)
at node.js:963:3


修改如下:

test_163:/home/exenode/es6 # more mytest.js
'use strict';
class Animal{
constructor(name){
this.name = name;
}

sayName(){
console.log('My name is ' + this.name);
}

}

class Programmer extends Animal{
constructor(name){
super(name);
}

program(){
console.log("I'm coding...");
}

}

var animal = new Animal('dummy');

var wayou = new Programmer('wyou');

animal.sayName();
wayou.sayName();

wayou.program();
test_163:/home/exenode/es6 #
test_163:/home/exenode/es6 # node mytest.js
My name is dummy
My name is wyou
I'm coding...
test_163:/home/exenode/es6 #
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: