JavaScript 中常量作为函数的输入?
在我的 js 文件中说,我希望
var NO = 0;
var YES = 1;
function doYouLikeCake(answer){}
当从另一个文件调用 doYouLikeCake 时,我希望能够输入 YES 或 NO,但我不确定如果这些变量是在 js 文件中定义的,该怎么做。这可能吗?
编辑:别介意 HTML 位。不,没有按钮。我正在尝试创建一个库,并希望简化它,以便库的用户可以只编写 doYouLikeCake(YES) 而不必自己定义 YES/NO 。
Say in my js file I want to have
var NO = 0;
var YES = 1;
function doYouLikeCake(answer){}
When doYouLikeCake is called from another file, I want to be able to input YES or NO, but I'm not sure how to do that if those variables are defined in the js file. Is this possible?
EDIT: Nevermind the HTML bit. No, there are no buttons. I'm trying to make a library, and want to simplify it so that the users of the library can just write doYouLikeCake(YES) rather than having to define YES/NO themselves.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
是的,你可以这样做:
Yes, you can do this:
样板文件是...
因此,您希望将“常量”放入名称空间中,这可以通过 IIFE(如上面的示例)或 DOM 就绪处理程序来实现。您的所有代码都应驻留在该名称空间内,这确保您的“常量”可用于您的代码。
顺便说一句,您可以通过创建不可写属性来创建真正的常量:
其中 APP 是常量的命名空间。
The boilerplate would be...
So, you want to put your "constants" inside your namespace, which can be achieved by an IIFE (like in my example above), or a DOM-ready handler. All your code should reside inside that namespace, which ensures that your "constants" are available to your code.
Btw, you can create real constants by creating non-writable properties:
where
APP
is the namespace for the constant.这是我上面评论中的示例: http://jsfiddle.net/vhQ8T/
here's the example from my comment above: http://jsfiddle.net/vhQ8T/
如果变量是在 js 文件中定义的,则需要从脚本动态更新 html 元素。
例如,这可能是您的 html:
和您的 js:
// 这些是您的变量
实时示例: http://jsfiddle.净/WhHXK/
If your variables are defined in the js file, you'll need to update the html element dynamically from the script.
For example this could be your html:
And your js:
// these are your variables
The live example: http://jsfiddle.net/WhHXK/
为什么需要输入它们。只需引用它们,因为它们是在全局范围内声明的。
Why do you need to input them. Just reference them since they are being declared in the global scope.