-2

为什么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');
4

3 回答 3

1

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);
    }
}  
var d = new Dog('Blacky');

console.log("returned", d.ageImmediate());
d.ageDelayed(function(age) {
    console.log("from callback", age);
});
于 2013-08-09T14:19:53.390 回答
1

这有效,但不像您期望的那样,您必须使用回调系统:

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.defered http://api.jquery.com/deferred.promise/

于 2013-08-09T14:20:03.697 回答
0

当您调用 age() 时,超时开始并且函数返回未定义,因为您没有在函数中返回任何内容。然后在 500 毫秒后触发超时并且该函数返回 10。

所以我不知道你想要这个函数做什么。

于 2013-08-09T14:28:04.810 回答