javascript - 如何从函数/实异常(exception)部访问变量

标签 javascript jquery oop instance

我有一个非常简单的 JavaScript 代码,应该使用参数 firstnamelastname 返回全名,当我在函数中提醒全名时,所有工作正常。但我正在努力如何使 fullname 变量可以从函数/实异常(exception)部访问?

这是我的代码:

var getName = function () {

    this.name = function (firstname, lastname, success) {
        var fullName = firstname + " " + lastname;
        success(fullName);
    };

};


var test = new getName();

test.name("John", "Smith", function (output) {
    var fullname = output;
    alert(fullname); //this works fine
    return fullname; // I need this variable to be accessed from outside this function
});

var myName = fullname; //I need to create the variable here
alert(myName); //this does not work

这是Fiddle

非常感谢您的帮助。

编辑:我正在构建一个 iPad 应用程序,其中使用 cordova 和 javascript 插件。 其中一个插件使我可以访问设备内的文件。现在,我需要能够获取路径并在回调之外使用它,以便我可以在范围内的任何位置使用:

这是插件代码:

var FileManager = function(){

this.get_path = function(todir,tofilename, success){
        fail = (typeof fail == 'undefined')? Log('FileManager','read file fail'): fail;
        this.load_file(
            todir,
            tofilename,
            function(fileEntry){

                var sPath = fileEntry.toURL();
                success(sPath);
            },
            Log('fail')
        );

    }


    this.load_file = function(dir, file, success, fail, dont_repeat){
        if(!dir || dir =='')
        {
            Log('error','msg')('No file should be created, without a folder, to prevent a mess');
            fail();
            return;
        }
        fail = (typeof fail == 'undefined')? Log('FileManager','load file fail'): fail;
        var full_file_path = dir+'/'+file;
        var object = this;
        // get fileSystem
        fileSystemSingleton.load(
            function(fs){
                var dont_repeat_inner = dont_repeat;
                // get file handler
                console.log(fs.root);
                fs.root.getFile(
                    full_file_path,
                    {create: true, exclusive: false},
                    success,

                    function(error){

                        if(dont_repeat == true){
                            Log('FileManager','error')('recurring error, gettingout of here!');
                            return;
                        }
                        // if target folder does not exist, create it
                        if(error.code == 3){
                            Log('FileManager','msg')('folder does not exist, creating it');
                            var a = new DirManager();
                            a.create_r(
                                dir,
                                function(){
                                    Log('FileManager','mesg')('trying to create the file again: '+file);
                                    object.load_file(dir,file,success,fail,true);
                                },
                                fail
                            );
                            return;
                        }
                        fail(error);
                    }
                );
            }
        );
    };
}

这是我的使用方法:

    var b = new FileManager(); // Initialize a File manager

    b.get_path('Documents','data.json',function(path){
        myPath = path;
        console.log(myPath); //this gives me the path of the file in the console, which works fine
        return myPath; //I return the path to be accessed outside
    });

    var filePath = myPath; //here I need to access the path variable
    console.log(filePath)// here, the path is undefined and it does not work

    //Since I'm using angular services to retrieve the data from json, I'd like to pass the filePath
  //this is a fraction of code for retrieving data:
  return $resource('data.json',{}, {'query': {method: 'GET', isArray: false}});

  //passing the value does not work
  return $resource(filePath,{}, {'query': {method: 'GET', isArray: false}});

  //even wrapping resource around instance does not work, it breaks the whole app
  b.get_path('Documents','data.json',function(path){
        myPath = path;
        console.log(myPath); //this gives me the path of the file in the console, which works fine
        return $resource(myPath,{}, {'query': {method: 'GET', isArray: false}});
    });

工厂服务:

'use strict';
angular
    .module ('myApp')
    .factory('getMeData', function ($resource) {
        var b = new FileManager(); // Initialize a File manager
        b.get_path('Documents','data.json',function(path){
            myPath = path;
            return myPath;
        });

        //below doesn't work when passing path (it is undefined)
        return $resource(myPath,{}, {'query': {method: 'GET', isArray: false}});

        //when wrapping it around, the app crashes
        b.get_path('Documents','data.json',function(path){
            myPath = path;
            return $resource(myPath,{}, {'query': {method: 'GET', isArray: false}});
        });

        //none of the solution above work

    });

最佳答案

如果您的 name 函数返回 success 的结果,那么您可以使用该方法的返回值。

var getName = function () {
    this.name = function (firstname, lastname, success) {
        var fullName = firstname + " " + lastname;
        return success(fullName);
    };

};


var test = new getName();

var myName = test.name("John", "Smith", function (output) {
    var fullname = output;
    alert(fullname); //this works fine
    return fullname; // I need this variable to be accessed from outside this function
});
alert(myName);

关于javascript - 如何从函数/实异常(exception)部访问变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27818260/

相关文章:

javascript - 检查 Javascript 命名空间中的类类型是否可用

具有从 `NameBase` 类到模板 `Name` 类的继承的 C++ 习惯用法(或模式)

javascript - 根据定义的 div 设置多个 div 高度

javascript - Angular.js 指令编译函数

jquery - 如何从 .bind() 中排除该元素?

javascript - jQuery Ajax 文件上传

python - 通过类创建 pandas DataFrame 返回空 DataFrame

javascript - 动态创建的元素上的事件绑定(bind)?

javascript - 为什么之前的背景颜色记录在变量C中?

javascript - 用 jQuery 制作下拉菜单