简体   繁体   English

常量作为JavaScript函数的输入吗?

[英]Constants as input to a function in JavaScript?

Say in my js file I want to have 在我的js文件中说

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. 当从另一个文件调用doYouLikeCake时,我希望能够输入YES或NO,但是我不确定如果在js文件中定义了这些变量,该怎么办。 Is this possible? 这可能吗?

EDIT: Nevermind the HTML bit. 编辑:不要介意HTML位。 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. 我正在尝试创建一个库,并希望对其进行简化,以便该库的用户只需编写doYouLikeCake(YES)即可,而不必自己定义YES / NO。

Yes, you can do this: 是的,您可以这样做:

<input type="submit" onclick="doYouLikeCake(YES);" value="Yes">
<input type="submit" onclick="doYouLikeCake(NO);" value="No">

<script>

    var NO = 0;
    var YES = 1;

    function doYouLikeCake(answer) { 
        //... 
    }

</script>

The boilerplate would be... 样板将是...

(function () {

    var YES = true;
    var NO = false;

    // All your JavaScript code here

}());

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. 因此,您想将“常量”放入命名空间中,这可以通过IIFE(如上面的示例)或支持DOM的处理程序来实现。 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: 顺便说一句,您可以通过创建不可写的属性来创建实常数:

Object.defineProperty( APP, 'YES', {
    value: true,
    enumerable: true
});

where APP is the namespace for the constant. 其中APP是常量的名称空间。

这是我上面的评论中的示例: http : //jsfiddle.net/vhQ8T/

If your variables are defined in the js file, you'll need to update the html element dynamically from the script. 如果您的变量是在js文件中定义的,则需要从脚本中动态更新html元素。

For example this could be your html: 例如,这可能是您的html:

<input type="radio" name="YesOrNo" id="NO" value="PlaceHolderForNo" />NO
<input type="radio" name="YesOrNo" id="YES" value="PlaceHolderForYes" />YES

And your js: 和你的js:

var NO=0;
var YES=1;

var inputNO=document.getElementById("NO");
var inputYES=document.getElementById("YES");

// these are your variables //这些是您的变量

inputNO.value=NO; 
inputYES.value=YES;

inputNO.onclick=function(){doYouLikeCake(this.value);};
inputYES.onclick=function(){doYouLikeCake(this.value);};

The live example: http://jsfiddle.net/WhHXK/ 实时示例: http : //jsfiddle.net/WhHXK/

Why do you need to input them. 为什么需要输入它们。 Just reference them since they are being declared in the global scope. 只需引用它们,因为它们是在全局范围内声明的。

function doYouLikeCake()
{
    return YES;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM