传递参数的Javascript类
Javascript class passing parameters
我已经创建了几个类,但在类本身上从来没有任何需要的参数。
下面的代码运行良好。
$(function()
{
search.anotherFunction('a', 'b');
});
search = function()
{
this.anotherFunction = function(param1, param2)
{
// do whatever
};
var public = { anotherFunction: anotherFunction }
return public;
}();
但现在我想在search
内部传递参数,以避免将相同的参数传递给所有函数。
$(function()
{
search('front/file.php').anotherFunction('a', 'b');
});
search = function(url)
{
this.anotherFunction = function(param1, param2)
{
// use here the 'url' parameter
};
this.anotherFunctionB = function(param1, param2)
{
// use here the 'url' parameter
};
var public = { anotherFunction: anotherFunction,
anotherFunctionB: anotherFunctionB }
return public;
}();
这不起作用,控制台会输出错误。
未捕获的类型错误:对象不是函数
这意味着search
不是函数,而是类名,因此不能接收params?
首先,创建"类"的方式不正确,最终会创建全局变量:在对匿名函数的调用中,由于调用方式的原因,this
将引用全局对象*,因此this.anotherFunction = ...
将创建一个名为anotherFunction
的全局变量,因为全局对象上的属性是全局变量。
如果你想继续使用你的当前模式,并尽量减少更改,那么不要在函数中使用this.xyz = ...
,而是使用var
:
var search = function()
{
var anotherFunction = function(param1, param2)
{
// do whatever
};
var public = { anotherFunction: anotherFunction }
return public;
}();
还要注意的是,您没有声明search
,从而成为隐式全局变量的恐怖的牺牲品;我添加了一个var
来声明它。
如果没有调用最外层的函数,只是将该函数分配给search
变量,然后稍后调用它,则第二个示例(具有上述更改)将起作用:
var search = function(url)
{
var anotherFunction = function(param1, param2)
{
// use here the 'url' parameter
};
var anotherFunctionB = function(param1, param2)
{
// use here the 'url' parameter
};
var public = { anotherFunction: anotherFunction,
anotherFunctionB: anotherFunctionB }
return public;
}; // <== Note, no () here
现在search
指的是一个函数,我们可以这样调用它:
var x = search("http://example.com");
x.anotherFunction(...); // Will have access to the URL
*当您调用匿名函数时,为什么this
引用全局对象?因为您调用它时没有执行任何操作来将this
设置为其他值,并且您使用的是松散模式。(我知道你使用的是宽松模式,因为如果你使用严格模式,this
将是undefined
,因此this.anotherFunction = ...
将失败。)
附带说明:我建议您停止使用public
作为变量名,因为它是未来的保留字,并且至少从ES3开始就使用了。
您可以在此处使用JavaScript闭包。查看以下方法:
search = function()
{
return function (url) {
this.anotherFunction = function(param1, param2)
{
// use here the 'url' parameter
};
this.anotherFunctionB = function(param1, param2)
{
// use here the 'url' parameter
};
var public = { anotherFunction: anotherFunction,
anotherFunctionB: anotherFunctionB }
return public;
}
}();
search('front/file.php').anotherFunction('a', 'b');
- 用于回调的javascript参数
- 我不能使用变量作为javascript参数
- Ajax.ActionLink-传递javascript参数
- 需要Javascript参数帮助
- NS_ERROR_XPC_BAD_CONVERT_JS:无法转换JavaScript参数arg 0[nsIDOMWind
- JavaScript参数验证
- 变量与表达式作为Javascript参数
- JavaScript参数对象不起作用
- 带有javascript参数的ASPNET MVC RenderAction
- IE JavaScript参数和填充输入字段
- 传递Javascript参数并分配给变量
- Jquery函数中提供Javascript参数
- 使用Play动态更改Javascript参数
- 函数中的 JavaScript 参数
- 本地化字符串中的 JavaScript 参数
- JQuery 函数突然停止工作,转换 Javascript 参数时出错
- JavaScript 参数对象 MDN 指南
- JavaScript 参数未跨处理程序传递
- 即时更改 Javascript 参数
- 附加到 JavaScript 参数中的所有值