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

时间:2017-03-04 09:23:55

标签: javascript callback

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

例如,在下面的代码中,将使用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>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

您应该使用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>

然而,与那些这个玩起来似乎有些混乱,我会尽量避免它们(例如使用工厂模式)