无法将值从函数传递到变量

cannot pass value from function to variable

本文关键字:变量 函数      更新时间:2023-09-26

所以,我有一段关于对象的代码

Obj.prototype.save = function (fn){
    var aabb = Obj.reEditName(this.name, function(newName) {
         return newName;
         // I also try the following
         var foo = newName; 
         return foo;
    });     
    console.log("aabb is  : "+aabb);
}
Obj.reEditName = function(name, fn){
    var name ? name : "TestingName";
    nameEditor(name,function(err, finalName) {
        return fn(finalName);
    });
}

Obj.reEditName运行良好,并且我可以从newName得到一个值。

console.log("aabb is : "+aabb);给出了未定义的反馈。

我不明白为什么。我得到一个值,然后返回它,aabb假设要捕获它。为什么这不起作用?如何将newName传递回aabb

感谢

您未定义的唯一原因是,newName未定义。。。让我们来看看您的代码。

Obj.prototype.save = function (fn){
    //I suppose here you are assigning aabb the result of reEditName.
    //because you are calling it...
    var aabb = Obj.reEditName(this.name, function(newName) {
         //you have a callback as a second parameter, and this callback recevied an argument (newName)...
         return newName;
         // I also try the following
         var foo = newName; 
         return foo;
    });     
    console.log("aabb is  : "+aabb);
}

这里的问题是,当您从reEditName方法调用回调时,没有接收到newName参数,或者由于其他原因接收到未定义的参数

可能的解决方案:

Obj.reEditName = function(name, callback) {
  //you should call that callback with an argument, and return it...
  return callback('New name');
}