2017-03-04 72 views
0

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

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

+1

难道你不能在回调函数中使用现有的'_this'变量而不是'this'吗? – nnnnnn

+0

@nnnnnn - 在这个简化的例子中,是的 - 我可以使用'_this.data'。不过,有很多次我希望回调的上下文被正确绑定。 – mseifert

回答

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>

仍然inheritate,似乎有点乱玩那些这个,我会t ry以避免它们(例如,使用工厂模式)