Javascript 类传递参数

标签 javascript

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

以下代码完美运行。

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

这不起作用,控制台会输出错误。

Uncaught TypeError: object is not a function

这意味着 search 不是一个函数,而是一个类名,因此无法接收参数?

最佳答案

首先,您创建“类”的方式不正确,最终创建了全局变量:在对匿名函数的调用中,由于您调用它的方式,this 将引用全局对象*,因此 this.anotherFunction = ... 将创建一个名为 anotherFunction 的全局变量,因为全局对象上的属性是全局变量。

如果您想以最小的更改继续使用当前模式,则不要在函数中使用 this.xyz = ... ,而是使用 var :

var search = function()
{
   var anotherFunction = function(param1, param2)
   {
      // do whatever
   };

   var public = { anotherFunction: anotherFunction }  

   return public;
}();

另请注意,您已成为 The Horror of Implicit Globals 的牺牲品不声明 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 作为变量名称,因为它是 future reserved word至少从 ES3 开始就是这样。

关于Javascript 类传递参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29329940/

相关文章:

javascript - 我怎样才能修复我的输出将是 2 个十进制数字 ex :(. 11) 或者它应该是 (.00)

javascript - 如何记录现有的 nodejs API?

javascript - 使用 Chrome 扩展程序检测警报

javascript - 几次点击后 Bootstrap 模式停止

JavaScript:如何获取给定函数对象的函数定义

javascript - 通过按钮动态传递值

javascript - 使用 jquery 更改某些 html 的位置以隐藏某些 html

JavaScript 对象、数组,混淆了吗?

javascript - 使用 Javascript 清除 &lt;textarea&gt;?

javascript - AngularJS:如何缓存从 $http 调用返回的 json 数据?