JavaScript 中的 private 和 public 这两个词到底有多保留
每次我构建一个 JS 库时,我都有这样的概念:
(function(window,undefined){
var LibName = function(){
var privateAPI = {
method: function(){}
};
var publicAPI = {
publicMethod: function(){}
};
return publicAPI;
}
window.LibName = LibName;
})();
但我一直渴望只是做:
(function(window,undefined){
var LibName = function(){
var private = {
method: function(){}
};
var public = {
publicMethod: function(){}
};
return public;
}
window.LibName = LibName;
})();
但我从来没有这样做过,因为那些是保留字。他们到底有多矜持呢?浏览器会失败吗?在我的测试中,一切似乎都有效,但我是否遗漏了一些东西?
Each time I build a JS library I have this sort of concept:
(function(window,undefined){
var LibName = function(){
var privateAPI = {
method: function(){}
};
var publicAPI = {
publicMethod: function(){}
};
return publicAPI;
}
window.LibName = LibName;
})();
But i've always longed for just doing:
(function(window,undefined){
var LibName = function(){
var private = {
method: function(){}
};
var public = {
publicMethod: function(){}
};
return public;
}
window.LibName = LibName;
})();
But I've never done that because those are reserved words. Just how reserved are they? Will a browser fail? In my testing, everything seems to work, but am I missing something?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
始终假设保留字使用不当会导致应用程序失败。
像
public
和private
这样的词是未来保留字,所以即使它们现在起作用,将来也可能不起作用。Always assume that using reserved words improperly will cause the application to fail.
Words like
public
andprivate
are future reserved words, so even if they work now the might not in the future.https://developer.mozilla.org/en/JavaScript/Reference/Reserved_Words
和
http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-262.pdf 了解官方规范。
它们在 7.6.1.2 中列为“保留供将来使用”。
https://developer.mozilla.org/en/JavaScript/Reference/Reserved_Words
and
http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-262.pdf for the official specification.
They're listed in 7.6.1.2 as "reserved for future use".
我不建议使用私人和公共。但是只有通过“use strict”使用严格模式才会出现错误: https://developer .mozilla.org/en/JavaScript/Strict_mode
如果您想确定它将来是否有效,则必须使用括号:
我更喜欢将 var 缩短为“pub”和“priv”。所以我使用这样的模式:
I would not recommend to use private and public. But you'll get an error only by using strict mode with "use strict": https://developer.mozilla.org/en/JavaScript/Strict_mode
If you want to be sure, it will work in the future, you would have to use parentheses:
I prefer to shorten the var to "pub" and "priv". So I use a pattern like this:
根据我在 javascript 中保留字的经验,代码会出现语法错误之类的错误。
From what I've experienced with reserved words in javascript the code will error out with something like a syntax error.