简体   繁体   English

在javascript函数范围内定义变量的最佳方法是什么?

[英]What's the best way to define a variable within the scope of a javascript function?

I would like to define variables within scope of paginate() . 我想在paginate()范围内定义变量。 However, any variable defined with this (eg this.parentlist ) is not available within the jQuery click method 但是,使用this定义的任何变量(例如this.parentlist )在jQuery click方法中不可用

var paginate = function(elt) {
          //would like to define variables within scope of paginate()
          //however, any variable defined with this (e.g. this.parentlist) is not available within the jQuery click method
          this.parentlist = elt.find('ul');
          var listitems = elt.find('li');
          this.listcount = this.list.find('li').size();
          var showitems = '3';

          this.numberofpages = ~~((this.count / this.show) + 1);

          this.parentlist.after('<ul class="links"></ul>');

          for(i=1;i<=this.numberofpages;i++) {
            $('.links').append('<li><a href="#'+i+'">'+i+'</a></li>')
          };

          //click a link
          $('.links a').click(function() {
            //this.parentlist is not available here
            listitems.hide();
            this.start = listitems.index() * showitems;
            this.end = (this.start + 1) * showitems;
            this.selected = listitems.slice(this.start,this.end).show().addClass('selected');
            console.log(this.selected);
            console.log(this.parentlist);
          }); 
  };

  paginate($('.pages'));

That is because inside click event handler this points to anchor element on which the event handler is attached. 这是因为里面click事件处理this点可以固定在其上的事件处理程序附加元素。

You have to declare a variable outside the handler and then use it. 你必须在处理程序之外声明一个变量然后使用它。 It will still be inside paginate function scope. 它仍然在paginate函数范围内。 Try this 尝试这个

var paginate = function(elt) {
          //would like to define variables within scope of paginate()
          //however, any variable defined with this (e.g. this.parentlist) is not available within the jQuery click method
          var parentlist = elt.find('ul');

          ..
          ..
          //click a link
          $('.links a').click(function() {

            //this.parentlist is not available here
            //Use parentlist instead of this.parentlist 
            ..
            ..

          }); 
  };

  paginate($('.pages'));

You use the var keyword to declare a variable within the current scope. 您可以使用var关键字在当前范围内声明变量。

//For example:
var paginate = function(){

    // create a local variable (local to "paginate function")
    var myvar = 7;

    // create the click handler
    $('.links a').click(function() {

        // access the local variable
        alert(myvar);

    });
}

The myvar variable is available "within" the click handler anonymous function because they were both declared "within" the same scope (the paginate function). myvar变量在单击处理程序匿名函数中“可用”,因为它们都在同一范围内(分页函数)声明。

However, once you're inside the anonymous function, this refers to the calling object of that function and not the function that it was declared in. If you need access to this as the "paginate" caller, then you can cache the this variable like others are saying: var that = this; 但是,一旦你进入匿名函数, this引用了该函数的调用对象而不是它所声明的函数。如果你需要访问this作为“paginate”调用者,那么你可以缓存this变量像其他人一样说: var that = this; <-- this is declaring a local variable (like above) and setting its value to this . < - 这是声明一个局部变量(如上所述)并将其值设置this值。

So, in your example, you can change it like this: 因此,在您的示例中,您可以像这样更改它:

var paginate = function(elt) {

      var parentlist = elt.find('ul');
      var listitems = elt.find('li');
      var listcount = this.list.find('li').size();
      var showitems = '3';

      var numberofpages = ~~((this.count / this.show) + 1);

      parentlist.after('<ul class="links"></ul>');

      for(i=1;i<=numberofpages;i++) {
        $('.links').append('<li><a href="#'+i+'">'+i+'</a></li>')
      };

      //click a link
      $('.links a').click(function() {
        //this.parentlist is not available here
        listitems.hide();
        this.start = listitems.index() * showitems;
        this.end = (this.start + 1) * showitems;
        this.selected = listitems.slice(this.start,this.end).show().addClass('selected');
        console.log(this.selected);
        console.log(parentlist);
      }); 
};

paginate($('.pages'));

In this particular example, it is better to declare parentlist as a var function paginate() 在这个特定的例子中,最好将parentlist声明为var函数paginate()

The variable will then be accessible in the click function enclosed in the paginate function. 然后可以在paginate函数中包含的click函数中访问该变量。

var paginate = function () {
     var parentlist = "some value";

     $('#selector').click(function () {
         alert(parentlist);
     });
};

Don't prefix your variables with this. 不要this.变量添加前缀this. . The this in the scope of paginate() is the global scope (window). paginate()范围内的this是全局范围(窗口)。

If you define it as var parentlist = elt.find('ul'); 如果将其定义为var parentlist = elt.find('ul'); , the parentlist will be available as is inside the click handler. parentlist将在点击处理程序中可用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 从控制器调用指令中的函数的最佳方法是什么 - What's the best way to call function within directive from controller 函数内创建对象的Javascript变量范围 - Javascript variable scope for objects created within function 处理 Javascript 中的可选 &amp;&amp; 动态 function 参数的最佳方法是什么? - What's the best way of dealing with optional && dynamic function parameters in Javascript? 根据Javascript中的类型对函数输入进行排序的最佳方法是什么? - What's the best way to sort function inputs based on type in Javascript? 在for()循环中声明的Javascript变量的范围是什么? - What's the scope of a Javascript variable declared in a for() loop? 在Javascript中定义数据的好方法是什么? - What's a good way to define data in Javascript? Javascript 变量未在函数的 Scope 中声明 - Javascript Variable Not Declaring in Function's Scope 定义函数的最佳方法是什么? - Best way to define a function? 将类回调保留在上下文/范围内的最佳JavaScript做法是什么? - What is best JavaScript practice for keeping class callbacks within a context / scope? 在JavaScript中格式化HTML,CSS和JavaScript代码的最佳方法是什么? - What's the best way to format HTML, CSS and JavaScript code within a JavaScript
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM