Javascript,在对象文字中传递函数,它是可调用的吗
Javascript, passing a function in an object literal and is it callable?
在学习Javascript和修改一个很酷的自动完成库的过程中,我现在站在了这个前面:
我需要检查在对象文字中传递的东西是一个变量/字段(被认为是一个简单的值(还是可以调用的东西。
(由于我的自动完成依赖于许多输入字段,我需要在Ajax.Request之前对正确的内容进行"赋值"(,以便此声明(请参阅"额外"部分…(
myAutoComplete = new Autocomplete('query', {
serviceUrl:'autoComplete.rails',
minChars:3,
maxHeight:400,
width:300,
deferRequestBy:100,
// callback function:
onSelect: function(value, data){
alert('You selected: ' + value + ', ' + data);
}
// the lines below are the extra part that i add to the library
// an optional parameter, that will handle others arguments to pass
// if needed, these must be value-ed just before the Ajax Request...
, extraParametersForAjaxRequest : {
myExtraID : function() { return document.getElementById('myExtraID').value; }
}
请参阅下面的"1//here i’m lost…",而不是1=>我想检查extraParametersForAjaxRequest[x]是否可调用,如果可调用则调用它,如果不可调用则只保留其值。这样,我就可以得到其他输入的正确值。。。同时保持一个真正通用的方法和对这个库的干净修改。。。
{
var ajaxOptions = {
parameters: { query: this.currentValue , },
onComplete: this.processResponse.bind(this),
method: 'get'
};
if (this.options.hasOwnProperty('extraParametersForAjaxRequest'))
{
for (var x in this.options.extraParametersForAjaxRequest)
{
ajaxOptions.parameters[x] = 1 // here i'm lost...
}
}
new Ajax.Request(this.serviceUrl, ajaxOptions );
您可以执行typeof来查看参数是否为函数,如果是则调用它。
var value;
for (var x in this.options.extraParametersForAjaxRequest)
{
value = this.options.extraParametersForAjaxRequest[x];
if (typeof(value) == 'function') {
ajaxOptions.parameters[x] = value();
}
else {
ajaxOptions.parameters[x] = value;
}
}
if (typeof this.options.extraParametersForAjaxRequest[x]==='function') {
}
你也应该这样做:
if (this.options.extraParametersForAjaxRequest.hasOwnProperty(x) {
if (typeof this.options.extraParametersForAjaxRequest[x]==='function') {
}
}
当遍历对象的属性时,否则您也可能会看到原型成员。
另一个建议是用你正在处理的东西的别名使它更可读。所以最终会是:
var opts = this.options.extraParametersForAjaxRequest;
// don't need to check for existence of property explicitly with hasOwnProperty
// just try to access it, and check to see if the result is
// truthy. if extraParametersForAjaxRequest isn't there, no error will
// result and "opts" will just be undefined
if (opts)
{
for (var x in opts) {
if (opts.hasOwnProperty(x) && typeof opts[x]==='function') {
}
}
}
相关文章:
- 如果我传递一个参数,则不会调用javascript函数
- 在函数中传递参数,然后调用onClick函数
- Angularjs将函数从控制器传递到指令(或从指令调用控制器函数)-带参数
- 什么's调用函数和传递函数的区别
- 如何将一个变量传递到另一个要调用的函数中-Javascript
- 将值传递给稍后调用的函数
- 从指令调用控制器函数(使用从指令传递的参数)
- 在传递链接时调用 javascript 函数
- 使用传递给函数的文本来调用 JavaScript 函数
- 在 PHP 循环中调用 js 函数,同时将 php 变量作为参数传递给其中一个函数
- 在 MVC3 中使用字符串调用 JS 函数时,在视图中传递多个参数
- 如何将参数传递给使用 setTimeout 调用的函数
- 将文字/对象/类传递给具有数千次调用的函数的内存含义
- 关于 JavaScript 函数调用传递此函数的说明
- 根据传递的参数调用 js 函数
- 是否可以传递立即调用的函数表达式的执行上下文
- 当我引入从函数调用传递的变量时,For 循环无法正常工作
- 从传递给函数的字符串调用 JavaScript 函数
- Javascript:如何使用apply方法传递参数数组,然后在被调用的函数中访问它
- 调用javascript函数并传递参数