在ES5中使用模塊模式時,調用this.methodName
會給我返回對象中的methodName。但在ES6它現在有一點點不同....如何使用ES6訪問返回對象(模塊模式)中的「公共」函數?
舊的方式(與ES5):
var moduleOld = (function() {
//private
var privateArray = [1,2,3,4];
return {
getItemCount: function() {
return privateArray.length;
},
getTotal: function() {
return this.getItemCount();
}
};
})();
//output
console.log(moduleOld.getTotal()); //4 <-- Now, I want the same results with ES6 syntax
新的方式(用ES6):
let moduleES6 = (()=> {
//private
let privateArray = [1,2,3,4];
return {
getItemCount:()=> {
return privateArray.length;
},
getTotal:()=> {
return this.getItemCount();
}
};
})();
//output
console.log("es6 ", moduleES6.getTotal()); //Uncaught TypeError: this.getItemCount is not a function
有辦法它周圍...
let moduleES6_2 = (()=> {
//private
let privateArray = [1,2,3,4];
return {
getItemCount:()=> {
return privateArray.length;
},
getTotal:()=> {
return moduleES6_2.getItemCount(); // I changed "this" to the module name, i.e. moduleES6_2
}
};
})();
//output
console.log("es6 calling by module name: ", moduleES6_2.getTotal()); //works! But what if I change the module's name? Then I have to also change the function call in the getTotal function.
這種方式,改變模塊的名稱應該不是太大的問題:
let moduleES6_3 = (()=> {
//private
let privateArray = [1,2,3,4];
function getItemCount() {
return privateArray.length;
}
return {
//getItemCount: getItemCount,
getTotal:()=> {
return getItemCount(); // I am calling the private method. Not the public method!
}
};
})();
//output
console.log("es6 by private method: ", moduleES6_3.getTotal()); //works! But I don't really use the method in the return object, but rather the private declared method.
如何使用ES6訪問返回對象(模塊模式)中的「公共」函數?
let moduleES6 = (()=> {
//private
let privateArray = [1,2,3,4];
function getItemCount() {
return privateArray.length;
}
return {
getItemCount:()=> {
return privateArray.length;
},
getTotal:()=> {
return this.getItemCount();//<-- how to access the public getItemCount method?
}
};
})();
在ES6模塊是語言的一部分('import','export'和朋友),所以沒有必要黑客喜歡「模塊模式」。 – georg
@georg AFAIK導入和導出不是由所有瀏覽器本地支持的。剛剛嘗試過Chrome 53.0.2785.143(64位) – thadeuszlay
_「新方法(使用ES6)」_這不是新方法,這是一種不同的方式。箭頭的功能很少有意義。 – zeroflagL