带有setTimeout的函数构造函数
function constructor with setTimeout
为什么本例中的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);
}
}
var d = new Dog('Blacky');
console.log("returned", d.ageImmediate());
d.ageDelayed(function(age) {
console.log("from callback", age);
});
这是有效的,但不是您所期望的,您必须使用回调系统:
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.defferedhttp://api.jquery.com/deferred.promise/
当您调用age()时,超时被启动,函数返回未定义,因为您在函数中没有返回任何内容。然后在500毫秒之后,超时触发,并且该函数返回10。
所以我不知道你想让这个函数做什么。
相关文章:
- 构造函数函数闭包变量
- 构造函数函数中的自执行函数的OO上下文/范围
- 为什么在构造函数函数中使用此关键字
- 正在将构造函数函数迁移到TypeScript
- 获取构造函数函数的最佳方式是在JavaScript中使用带名称空间的字符串表示
- 为什么可以't我使用'var'在构造函数函数中
- 获取自定义对象构造函数函数名
- 在构造函数函数中创建只读(get)属性
- 正在检查类型构造函数函数
- Javascript中的内置构造函数函数
- 如何在JavaScript中的函数(函数本身就是一个参数)中传递参数
- 构造函数函数原型可枚举
- 为什么要设置原型's构造函数转换为其构造函数函数
- 从另一个javascript程序调用函数-函数式编程
- 构造函数函数.可以't覆盖对全局变量的引用
- 使用构造函数函数的Javascript继承
- 从数组构造生成器函数
- 如何创建DOM's构造函数函数
- 使用构造函数函数添加和删除项的数据结构
- 在NodeJS中构造helper函数的最佳方式