Javascript:如何称呼这个.Something() from this.img.onload = SomeLoa
Javascript: How to call this.Something() from this.img.onload = SomeLoadFunction;
好的,我有一些类似的代码...
Thing function () {
var img = new Image;
DoSomeStuff function() {
//Some stuff here that can't be done until my img is loaded...
};
InitMe function(src) {
this.img.onLoad = this.DoSomeStuff;
this.img.src = src;
};
}
var Test = new Thing();
Test.InitMe("some string");
这显然是行不通的,因为this.DoSomeStuff
不再Thing.DoSomeStuff
并变得img.DoSomeStuff
所以我想我需要知道的是,如何从img.onLoad
调用Thing.DoSomeStuff()
函数......
在 ES5 上,您可以使用:
this.img.onLoad = this.DoSomeStuff.bind(this);
或:
var self = this;
this.img.onLoad = function() {
self.DoSomeStuff();
}
附言:您当前的代码并不合法。 除此之外,变量的作用域错误(或者不是this
的属性),并且函数声明语法不正确。
你可能想要这个
function Thing() {
this.img = new Image;
this.DoSomeStuff=function(){
// do something
};
var self=this;
this.InitMe=function(src) {
self.img.src = src;
self.img.onload = function(){
self.DoSomeStuff();
}
};
}
var Test = new Thing();
Test.InitMe("example.png");
演示。
相关文章:
- $(this).prop('property') vs. this.property
- Twitter Bootstrap typeahead:使用“this”获取上下文/调用元素
- 在另一个函数中使用变量this
- this.router在AngularJS 2中未定义
- reactjs this.refs vs document.getElementById
- JavaScript 中的嵌套函数和 “this” 关键字
- React+Meteor:this.ops返回未定义
- javascript中对象构造函数中的var属性与this.properties
- 函数中this和var之间的区别
- jQuery(this).Pparent().Pparente().Prent().find()在iPad上不起作用
- Understanding Javascript scope with "var that = this&qu
- 定义this.properties或objectName.properties的javascript JSON对象
- Object.prototype using 'this'
- 在JavaScript类型的函数中避免self-this
- Validate JSON from Mongo?
- 如何使用(this)访问Angular 2 http rxjs catch函数中的对象属性
- Get JSON from an url
- Javascript:如何称呼这个.Something() from this.img.onload = SomeLoa
- 使用this from函数在作用域上获取/设置角度变量
- Access $(this) from a .toggle