var name = 'Bob'; var speak = `My name is ${name}`; // My name is Bob
3.多行字符串
在ES6之前,多行字符串需要用+号和换行符进行拼接;ES6可以直接把字符放到反引号里面即可。
1 2 3 4 5
var roadPoem = `Then took the other, as just as fair, And having perhaps the better claim Because it was grassy and wanted wear, Though as for that the passing there Had worn them really about the same.`
(function(){ var len = 5; for(var i = 0; i < len; i++ ){ console.log(i); // 0,1,2,3,4 } console.log(i); // 5 for(let n = 0; n < len; n++){ console.log(n); // 0,1,2,3,4 } console.log(n); // Uncaught ReferenceError: n is not defined })()
9.class类
在ES6之前使用构造函数方式。
1 2 3 4 5 6 7 8 9
function People(name, age){ this.name = name; this.age = age; this.speaking = function(){ return 'My name is' + this.name; }; } var boy = new People('Bob', 18); console.log(boy.speaking()); // 'My name is Bob'
ES6使用class定义类,更加规范。
1 2 3 4 5 6 7 8 9 10 11
classPeople{ constructor(name, age){ this.name = name; this.age = age; } speaking(){ return'My name is' + this.name; } } var girl = new People('Lina', 19); console.log(girl.speaking()); // 'My name is Lina'