【问题标题】:JavaScript Scope questionJavaScript 范围问题
【发布时间】:2011-04-09 21:03:09
【问题描述】:

作为一个试图对我的 javascript 编程采用更面向对象的方法的人,我遇到了一个绊脚石,我确信这可能是非常基本的东西,但是,采用以下对象实现(假设 jQuery 对象可用于此代码):

function Foo()
{
    this.someProperty = 5;
}

Foo.prototype.myFunc = function()
{
    //do stuff...
};

Foo.prototype.bar = function()
{
    //here 'this' refers to the object Foo
    console.log(this.someProperty);

    $('.some_elements').each(function()
    {
        //but here, 'this' refers to the current DOM element of the list of elements
        //selected by the jQuery selector that jquery's each() function is iterating through
        console.log(this);

        //so, how can i access the Foo object's properties from here so i can do
        //something like this?
        this.myFunc();
    });
};

【问题讨论】:

    标签: javascript oop scope


    【解决方案1】:

    您可以暂时使用另一个变量来指向正确的this

    Foo.prototype.bar = function()
    {
        //here 'this' refers to the object Foo
        console.log(this.someProperty);
    
        var self = this;
    
        $('.some_elements').each(function()
        {
            self.myFunc();
        });
    };
    

    【讨论】:

      【解决方案2】:

      在您输入传递给eachfunction 之前,您需要在一个变量中捕获外部函数的this,然后使用您传递给eachfunction 内部的变量。

      function Foo()
      {
          this.someProperty = 5;
      }
      
      Foo.prototype.myFunc = function()
      {
          //do stuff...
      };
      
      Foo.prototype.bar = function()
      {
          // in here, this refers to object Foo
      
          // capture this in a variable
          var that = this;
      
          $('.some_elements').each(function()
          {
              // in here, this refers to an item in the jQuery object
              // for the current iteration   
      
              console.log(that);
              that.myFunc();
          });
      };
      

      正如您所发现的,您传递给each 的函数内部的this 指的是每次迭代时jQuery 对象中的当前项,即第一次迭代指的是属性0 处的项,第二次迭代指的是属性 1 中的项目,等等。

      【讨论】:

        【解决方案3】:

        您正在发现JavaScript closures 的用处。它们对于编写简洁的代码非常强大和有用。这是您可以尝试理解的最有用的 JavaScript 功能之一。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-10-24
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多