【问题标题】:Access class members from anonymous function in javascript从javascript中的匿名函数访问类成员
【发布时间】:2012-05-09 12:21:06
【问题描述】:

我知道当我需要访问类成员函数时,我必须在 JS 类中保留对 this 的引用。但是,我目前正在努力处理以下(简化的)代码:

function MySimpleClass(p, arr) {
this.proxy = p;
this.contentArray = arr;

this.doStuff = function(callback) {
    var self = this;

    // at this point this.contentArray holds data

    this.proxy.calculate(function(data) {

        // inside the anonymous function this.contentArray is undefined

        var el = self.contentArray[0]; // <-- will fail
        // do something with el

        callback.call(this, data); 
    });
}}

感谢任何帮助!

【问题讨论】:

  • 这段代码对我来说不会失败。
  • 哦,不过还是谢谢你看一看。

标签: javascript function scope anonymous


【解决方案1】:

您的班级的这个示例代码正在运行:

var c = new MySimpleClass({calculate: function(f) {f()}}, [1,2]);
c.doStuff(function(){alert("hi");})

我假设您的代码不起作用,因为您还在代理类本身中定义了一个“自我”变量。您可以通过将班级中的“self”重命名为任意名称来检查:“selfXXX”

【讨论】:

    【解决方案2】:

    将 contentArray 作为参数发送给这个匿名函数怎么样,而不是只发送“数据”?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-08
      • 2016-03-15
      • 1970-01-01
      • 2010-09-26
      • 2015-05-04
      • 1970-01-01
      相关资源
      最近更新 更多