【问题标题】:Get the context of a object directly from the object itself直接从对象本身获取对象的上下文
【发布时间】:2017-03-04 09:23:55
【问题描述】:

我想直接从对象本身获取对象的上下文。

例如,在下面的代码中,将使用mousedown 事件调用回调函数。它工作正常,因为我使用this.callback.bind(this)) 绑定回调。

作为一个界面,这是相当笨重的。我希望能够简单地传递this.callback 并从MyClass2 中找出回调函数的上下文并将其绑定到接收端。这可能吗?

function MyClass1() {
  var _this = this;
  this.data = "Foo";
  var div = document.getElementById("div");
  this.callback = function() {
    console.log("Callback: " + this.data);
  }
  var m2 = new MyClass2(div, this.callback.bind(this));

}

function MyClass2(div, callback) {
  var _this = this;

  // I'd like to bind callback to the context it had when it was passed here
  // e.g. this.callback = callback.bind(callback.originalContext);
  this.callback = callback;

  div.addEventListener("mousedown", function(e) {
    _this.mousedown.call(_this, e)
  });

  this.mousedown = function() {
    console.log("Mousedown");
    this.callback();
  }
}

var m1 = new MyClass1();
<div id="div" style="background-color:azure; height:100%; width:100%">
  Click me
</div>

【问题讨论】:

  • 你不能在回调函数中使用现有的_this 变量,而不是this
  • @nnnnnn - 在这个简化的示例中,是的 - 我可以使用 _this.data。但是,很多时候我希望正确绑定回调的上下文。

标签: javascript callback


【解决方案1】:

您可能应该使用 Object.create 让您的 MyClass1 继承自 MyClass2

function MyClass1() {
  var _this = this;
  this.data = "Foo";
  var div = document.getElementById("div");
  var callback = function() {
    console.log("Callback: " + this.data);
  }
  MyClass2.call(this, div, callback);
}

function MyClass2(div, callback) {
  var _this = this;

  // I'd like to bind callback to the context it had when it was passed here
  // e.g. this.callback = callback.bind(callback.originalContext);
  this.callback = callback;

  div.addEventListener("mousedown", function(e) {
    _this.mousedown.call(_this, e)
  });

  this.mousedown = function() {
    console.log("Mousedown");
    this.callback();
  }
}

MyClass1.prototype = Object.create(MyClass2.prototype);
var m1 = new MyClass1();
<div id="div" style="background-color:azure; height:100%; width:100%">
  Click me
</div>

不过,玩这些 this 似乎有点乱,我会尽量避免它们(例如,使用工厂模式)

【讨论】:

    猜你喜欢
    • 2023-03-09
    • 2016-10-07
    • 1970-01-01
    • 2011-11-20
    • 1970-01-01
    • 2021-08-05
    • 2010-12-28
    • 2011-02-11
    • 1970-01-01
    相关资源
    最近更新 更多