![](/img/trans.png)
[英]calling an object method with a setTimeout function from within the same object in Javascript
[英]Use value from method in javascript object to use in setTimeout function
我尝试了不同的方法,但是我似乎确实在寻找一些显而易见的东西。 尝试使用函数(方法)返回的值在对象内部,并在同一对象内具有setTimeout的另一种方法中使用它。
这是html:
<h1>3000</h1>
javascript(在这种情况下为jQuery):
var foo = {
getValue: function() {
var h1Text = $('h1').text();
h1Text = parseInt(h1Text);
return h1Text;
},
useValue: function() {
var time = this.getValue();
var alertIt = alert('Hello');
setTimeout(alertIt,time);
}
};
foo.useValue();
// log shows correct value
console.log(foo.getValue());
// returns a number
console.log(typeof(foo.getValue()));
警报确实会显示,但是会在加载时而不是使用这3秒钟。 它确实记录了正确的值,并且还说它是一个数字,所以我真的不确定自己在做什么错。 任何帮助表示赞赏。 谢谢
setTiimeout
需要功能而不是变量。 也是var alertIt = alert('Hello');
这将返回未定义。
注意: var a = function()
将调用它并分配返回值。 要将函数分配给带有参数的变量,请使用.bind
尝试alert.bind(null, "hello");
出于演示目的,我对delay进行了硬编码,并注释了getValue
代码。
var foo = { getValue: function() { //var h1Text = $('h1').text(); //h1Text = parseInt(h1Text); return true// h1Text; }, useValue: function() { var time = 3000//this.getValue(); var alertIt = alert.bind(null,'Hello'); setTimeout(alertIt, time); } }; foo.useValue(); // log shows correct value console.log(foo.getValue()); // returns a number console.log(typeof(foo.getValue()));
在useValue()
您调用alert('Hello')
,因此它会立即执行并将结果存储在alertIt
变量中。 您应该将其放在这样的函数中,因为setTimeout
期望将函数作为第一个参数:
var alertIt = function() {
alert('Hello');
}
setTimeout(alertIt,time);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.