新定义函数

时间:2016-12-08 16:14:28

标签: jquery function parameters namespaces

当我在函数中定义一个函数并且两者共享相同的可变量名称时会发生什么? e.g:

$(document).ready(

$("a").on("click", function( event )
{
   // function code goes here
   function newfunction( event )
   {
     // function code dependant on parameter "event" goes here. 
     // Is "event" now a new variable totally independant to the first 
     // parameter "event". Were do I find something concerning the 
     // topic in the jQuery documentary?
   }
}

);

);

是第二个"事件"第6行完全独立于第一个"事件"在第3行?我决定在纪录片

中找到任何名称空间

http://learn.jquery.com/about-jquery/

的jQuery。我在哪里看?

2 个答案:

答案 0 :(得分:0)

newfunction上的event是一个参数。因此,它的值将是调用时传递给该方法的任何值。它不直接与点击处理程序上的参数绑定。如果您希望它是单击处理程序中的事件参数,则不要将该名称放在newfunction方法上。来自click处理程序的事件在调用它时将在newfunction中可用,因为它是在click处理程序的范围内定义的。

答案 1 :(得分:0)

从我的评论:它们是不同的变量。是。这是一个javaScript功能,而不是jQuery。尝试搜索“javascript参数范围”或类似内容。

忽略其他细节,你只需要嵌套2个函数。参数变量的范围仅在该函数的大括号内。

function a(p1){
  // Can only see p1 here
  function b(p2){
    // can see p2 and p1 here
  }
}

如果名称与外部变量的名称匹配,则与代码最接近的范围

function a(p){
  // Can only see first p here
  function b(p){
    // can see second p here as the first is now hidden by the new definition
  }
}