问题描述
好的,我在 JavaScript 中遇到了问题,我创建了一个函数构造函数,并添加了一个方法在调用它时具有的属性和方法,以使用对象环境方法作为基本示例,因为我的构造函数太复杂了.
Ok I have a problem in JavaScript I have created an Function Constructor and added a properties and methods one method has when it's called to work with the object environment methods as a basic example as my constructor is too complex.
function Construct(){
this.alert = 'test1';
this.replace = '';
this.interval;
this.run = function(){
console.log(this);//echo the constructor
this.interval = setInterval(function(){
console.log(this);//echo the window object
alert(this.alert);
this.replace = '';
}
};
}
如果您已阅读代码,您必须了解原因,这将失败.
This fails if you have read the code you must understand why.
如何将构造函数对象(this)传递给设置间隔函数?
how could I pass the constructor object (this) to the set interval function?
我尝试过使用外部函数并将其作为参数传递,但它失败了,因为替换仍然是它的原样并且它只有一次符文,为什么?
I have tried using external functions and pass this as an arguments but it fails miserably as replace is still as it is and it is runes only once why?
请帮忙.
谢谢.
推荐答案
创建一个本地self
变量,并设置为this
,这样你就可以在您的嵌套函数:
Create a local self
variable, and set it to this
, so that you can use that in your nested function:
function Construct () {
this.alert = 'test1';
this.replace = '';
this.interval;
this.run = function () {
var self = this;
this.interval = setInterval(function () {
self.replace = '';
}, 500);
};
}
这篇关于将此对象在构造函数中传递给 setIntervall的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!