Joh*_*ohn 2 javascript object settimeout setinterval
怎么可以在this里面使用setInterval和setTimeout调用?
我想用它像:
function myObj() {
this.func = function(args) {
setTimeout(function() {
this.func(args);
}, 1000);
}
}
Run Code Online (Sandbox Code Playgroud)
前段时间我用.onclick这种方式做了事:
this.click = function(func) {
this.elem.onclick = (function(func, obj) {return function(){func.apply(obj)} })(func,this);
};
Run Code Online (Sandbox Code Playgroud)
但我不知道我能为做intervals和timeouts.
最简单的方法就是保存this到本地.本地self不受具体的上下文改变setInterval和setTimeout回调调用.它将保持原始this值
function myObj() {
var self = this;
this.func = function(args) {
setTimeout(function() {
self.func(args);
}, 1000);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2322 次 |
| 最近记录: |