值我認爲你應該看到這一點:
var doc, bod, htm, Img, C, E; // for reuse on other loads
addEventListener('load', function(){
doc = document; bod = doc.body; htm = doc.documentElement;
C = function(tag){
return doc.createElement(tag);
}
E = function(id){
return doc.getElementById(id);
}
Img = function(src, complete, context){
this.image = C('img');
var img = this.image;
var cx = context || this;
img.addEventListener('load', function(eventObj){
complete.call(cx, eventObj);
});
img.src = src;
this.imgMethod = fuction(){
this.newProp = 'this in here refers to instance of Img';
}
}
Car = function(){
this.setImg = function(src, complete){
return new Img(src, complete);
}
}
var what = new Car; // no args it's okay to not use() with new
var someImg = what.setImg('yourImgSrc.png', function(){
this.imgMethod(); console.log(this.newProp);
});
someImg.image.addEventListener('click', function(ev){
var bc = this.getBoundingClientRect();
var xy = {x:ev.clientX-bc.left, y:ev.clientY-bc.top};
console.log(xy);
});
});
注意:這僅僅是一個使用call
你能嘗試做結合的
this
例如:( 「圖像加載」 + this.bounds)this.image.onload =函數(){ 的console.log; } .bind(this) – binariedMe沒問題。你能否加一點解釋綁定的用途。我會接受答案。謝謝! – kofhearts
你可以考慮這個。圖像「到」var「,然後使用'varName.bounds',所以'this'不再綁定到當前對象。您也可以創建另一個構造函數,然後在其他構造函數中定義的方法內返回一個新實例。 – PHPglue