简体   繁体   English

在封闭期间访问班级成员

[英]Access to class member within closure

I have a class method and a closure within this method. 我有一个类方法和此方法内的闭包。 How I can access to class member from closure? 我怎样才能从闭包访问班级成员?

Person = function(x) {
  this.x = x;
}

Person.prototype = {
   myMethod: function() {
      $('#myBtn').click( function() {
         // how to access to this.x? the this reference points in another context 
      });
   }
}

Use of Function.prototype.bind will help you here 使用Function.prototype.bind将为您提供帮助

Person = function(x) {
  this.x = x;
}

Person.prototype.myMethod = function() {
  $('#myBtn').click(function() {
    this.x;
  }.bind(this));
};

You can use some better separation of code here too 您也可以在此处使用更好的代码分离

Person = function(x) {
  this.x = x;
};

Person.prototype.myMethod = function {
  $('#myBtn').click(this.clickHandler.bind(this));
};

Person.prototype.clickHandler = function(event) {
  console.log(this.x);
};

Note if you want to support older browsers, check out es5-shim 请注意,如果您想支持较旧的浏览器,请查看es5-shim


EDIT 编辑

I'm revisiting this after ~6 months and I would probably write the above code differently. 大约6个月后,我将重新讨论这一点,我可能会以不同的方式编写以上代码。 I like the private/public exposure here. 我喜欢这里的私人/公共场合。 Also, no need for any fanciful binds or anything like that ^.^ 同样,也不需要任何幻想的绑定或类似的^。^

function Person(x, $button) {

  // private api
  function onClick(event) {
    console.log(x);
  }

  function myMethod() {
    $button.click();
  }

  // exports
  this.x        = x;
  this.myMethod = myMethod;

  // init
  $button.click(onClick);
}

var b = $("#myBtn"),
    p = new Person("foo", b);

p.x;          // "foo"
p.myMethod(); // "foo"
btn.click();  // "foo"

Just assign this to some other variable, for example _this : 刚分配this给一些其他的变量,例如_this

Person = function(x) {
    this.x = x;
}

Person.prototype = {
    myMethod: function() {
        var _this = this;
        $('#myBtn').click( function() {
            console.log(_this.x);
        });
    }
}
Person = function(x) {
  this.x = x;
}

Person.prototype = {
   myMethod: function() {
      var self = this;
      $('#myBtn').click( function() {
         // Access to self.x 
      });
   }
}

A proxy would be very useful here. 代理在这里非常有用。

Right now, you're assigning an anonymous function to the click event. 现在,您正在为click事件分配一个匿名函数。 By default the context will be the event's and separate from your object. 默认情况下,上下文将是事件的上下文,并且与您的对象分开。

With a proxy you can assign a particular context to a (callback) function. 使用代理,您可以将特定的上下文分配给(回调)功能。 Thus, when the event fires, you're dealing with your person object. 因此,当事件触发时,您正在处理人对象。

  1. Assign the event handler in a separate function like initialize() , and have myMethod() be the handler. 在单独的函数(如initialize()分配事件处理程序,并使myMethod()作为处理程序。
  2. Use a JQuery.proxy() to assign the object`s context to the event handler. 使用JQuery.proxy()将对象的上下文分配给事件处理程序。

     Person.prototype = { initialize: function() { $('#myBtn').click($.proxy(this.myMethod, this)); }, myMethod: function(event) { ... console.log(this); // Person object } } 

Just to elicit the difference between my and @naomik's solution: 只是为了找出我和@naomik解决方案之间的区别:

  • JQuery.proxy() is a temporary or narrow assignment to a context. JQuery.proxy()是对上下文的临时或狭窄分配。
  • Function.prototype.bind() is a strong context assignment. Function.prototype.bind()是一个强大的上下文分配。 The method will be "forever" bound to the context you give it. 该方法将“永远”绑定到您提供的上下文中。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM