2017-03-04 38 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以避免它們(例如,使用工廠模式)