在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