传递参数的Javascript类

Javascript class passing parameters

本文关键字:Javascript 参数      更新时间:2023-09-26

我已经创建了几个类,但在类本身上从来没有任何需要的参数。

下面的代码运行良好。

$(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');