1.作用域隔離:es6作用域隔離採用一對花括號{}來隔離,而es3/es5採用立即執行函數((function(){})())進行作用域隔離;
2.this的指向:es6中的this是定義時this的指向,而es3/es5中this指向的是被調用者的對象,如下例子:
//ES6
{
var factory = function(){
this.a = 'a';
this.b = 'b';
this.c = {
a:'A+',
b:()=>{
return this.a;
}
};
}
console.log(new factory().c.b());//打印出 a。因爲調用的b()函數裏的this指向的是函數b定義時的factory函數體中的this,即factory本身
}
//ES3/ES5
{
var factory = function(){
this.a = 'a';
this.b = 'b';
this.c = {
a:'A+',
b:function(){
return this.a;
}
};
}
console.log(new factory().c.b());//打印出 A+。因爲調用的b()函數裏的this指向的是b()函數被調用的對象c,所以b()函數的this.a返回的是c對象裏的a
}
3.默認參數、必填參數的寫法:
//ES3/ES5 默認參數的寫法,另外必選參數也是採用這種方式,if判斷然後提示必填的信息
{
function f(x,y,z){
if(y===undefined){
y=7;
}
if(z===undefined){
z=42;
}
return x+y+z;
}
console.log(f(1,3));//46 1+3+42=46
}
//ES6 默認參數的寫法
{
function f(x,y=7,z=42){
return x+y+z;return x+y+z;
}
console.log(f(1,3));//46 1+3+42=46
};
//ES6必選參數寫法
{
function checkParameter(){
throw new Error('can\'t be empty!');
};
function fn(x=checkParameter(),y=7,x=42){
return x+y+z;
};
console.log(fn(1));//50 1+7+42
// fn();
//捕獲異常處理
try {
fn();//參數爲空時,會報異常
} catch (error) {
console.log(error);
}
}
4.可變參數,ES6使用...擴展運算符,而ES3/ES5使用arguments
//ES3/ES5 傳遞可變參數的寫法
{
// function fn(x){
// console.log(x);
// }
// console.log(fn(1,2,3));//1
function fn(){
var a = Array.prototype.slice.call(arguments);//arguments是僞數組
var sum=0;
a.forEach(function(item){
sum += sum*1;
});
return sum;
}
console.log(fn(1,2,3));//6
}
//ES6 傳遞可變參數的寫法
{
function fn(...a){
var sum=0;
a.forEach(item=>{
sum += sum*1;
});
return sum;
}
console.log(fn(1,2,3));//6
}
5.合併數組:ES6使用...擴展運算符,ES3/ES5使用concat():
//ES5合併數組寫法
{
var arr = ['hello',3,true];
var other = [1,2].concat(arr);
console.log(other);//[1,2,'hello',3,true]
}
//ES6合併數組寫法
{
var arr = ['hello',3,true];
var other = [1,2,...arr];
console.log(other);//[1,2,'hello',3,true]
}
6.對象代理,對對象數據的保護
//數據保護,對象代理
//ES3對象數據保護的寫法
var Person = function(){
var data={
name:'Jom',
age:19,
sex:'male'
}
this.get=function(key){
return data[key];
}
this.set=function(key,value){
if(key!=='sex'){
data[key] = value;
}
}
}
var person = new Person();
console.log("ES3:",person.get('name'));//Jom
person.set('name','張三')
person.set('sex','female')
console.log(person.get('name'));//張三
console.log(person.get('sex'));//male 此修改無效,因爲sex受保護不可修改
//ES5對象數據保護的寫法
var Person = {
name:'Rose',
age:19
}
Object.defineProperty(Person,'sex',{
value:'male',
writable:false
});
console.log("ES5:",Person.name);
try {
Person.sex='female';
console.log(Person.sex);//male 此修改無效
} catch (error) {
console.log(error);
}
//ES6對象數據保護的寫法
let Person1 = {
name:'Baby',
age:30,
sex:'female'
}
let Per = new Proxy(Person1,{
get(target,key){
return target[key]
},
set(target,key,value){
target[key] = value
}
});
console.log("ES6:",Per.name);//Baby
try {
Per.sex='female';
console.log(Per.sex);//male 此修改無效
} catch (error) {
console.log(error);
}