Javascript 具有setTimeout的函数构造函数
为什么本例中的Javascript 具有setTimeout的函数构造函数,javascript,Javascript,为什么本例中的d.age()不起作用 function Dog(input) { this.name = input; this.color = function(){ return 'black'; } this.age = function(){ setTimeout(function(){ return '10'; }, 500); } } window.d = n
d.age()
不起作用
function Dog(input) {
this.name = input;
this.color = function(){
return 'black';
}
this.age = function(){
setTimeout(function(){
return '10';
}, 500);
}
}
window.d = new Dog('Blacky');
Javascript没有“等待”。您可以立即返回,也可以稍后执行回调:
function Dog(input) {
this.name = input;
this.color = function() {
return 'black';
}
// returning a value works just fine:
this.ageImmediate = function() {
return 10;
}
// but if we want to return after a delay, we have to use a callback
this.ageDelayed = function(cb) {
setTimeout(function(){
cb(10);
}, 500);
}
}
这是可行的,但并非如您预期的那样,您必须使用回调系统:
function Dog(input) {
this.name = input;
this.color = function(){
return 'black';
}
this.age = function(callback){
setTimeout(function(){
callback('10');
}, 500);
}
}
window.d = new Dog('Blacky');
d.age(function(age){
// do some stuff with age
});
另外,请看jquery.deffered,调用age()时会启动超时,函数返回undefined,因为函数中不返回任何内容。然后在500毫秒后,超时触发,该函数返回10
所以我不知道你想要这个函数做什么 它确实有效。但是
return
ing在setTimeout
中不起任何作用,因为它是异步的。setTimeout
的返回值是一个“id”。您需要将回调传递给this.age
以在达到超时时执行,这样您就可以访问该“10”
(或任何值):您的确切意思是什么?您甚至没有显示对您所说的不起作用的函数的调用。请注意,不要在您想要的数字10
处使用字符串'10'
function Dog(input) {
this.name = input;
this.color = function(){
return 'black';
}
this.age = function(callback){
setTimeout(function(){
callback('10');
}, 500);
}
}
window.d = new Dog('Blacky');
d.age(function(age){
// do some stuff with age
});