簡體   English   中英

如何從函數/實例外部訪問變量

[英]how to access a variable from outside a function/instance

我有這個非常簡單的JavaScript代碼,應該使用參數firstnamelastname返回全名。當我在函數中提醒全名時,All都可以正常工作。 但是我正在努力如何使fullname變量可以從函數/實例外部訪問?

這是我的代碼:

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

這是小提琴

非常感謝您的幫助。

編輯:我正在構建一個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的結果,那么您可以使用方法中的return。

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);

在回調之外定義fullname

var getName = function () {

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

};


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

alert(fullname);

希望能幫助到你。 小提琴

如果需要異步:

假設實際的代碼源是一個異步代碼,現在已從您的注釋中確認,您應該只在回調中處理結果。 該值在回調之外根本不可用,因為結果稍后到達。

@Jim和@ bestmike007的答案不適用於異步操作,因為它從回調內部返回一個值,該回調可能在函數運行很長時間后發生。 (注意:@ bestmike007確實在注釋中鏈接了一個改進的答案)。

例如,看看這里發生了什么: http : //fiddle.jshell.net/y1m36w9p/1/或這里http://jsfiddle.net/TrueBlueAussie/opczeuqw/1/

使用異步代碼的唯一方法是異步方式。 這意味着您只能在回調內部處理結果:

// Get the fullname asyc and process the result
test.name("John", "Smith", function (fullname) {
    alert(fullname); // you can only work with the result in here
});

另一種方法是返回一個jQuery promisegetName.name()但最終的結果仍然是回調做的工作,但是這一次它是這樣的:

test.name("John", "Smith").done(function(fullname){
    alert(fullname); // you can only work with the result in here
});

但這是更多的代碼和復雜性,暫時沒有額外的好處。

對於您特定的更新示例代碼:

我對Angular不夠熟悉,無法確認這一點,因此需要了解如何getMeData ,但是您應該使用另一個回調作為注冊的getMeData函數的參數:

'use strict';
angular
    .module ('myApp')
    .factory('getMeData', function ($resource, callback) {
        var b = new FileManager(); // Initialize a File manager
        b.get_path('Documents','data.json',function(path){
            callback($resource(path,{}, {'query': {method: 'GET', isArray: false}}));
        });
    });

如果異步不需要 (廢棄的選項)

如果(如下面先前的矛盾評論所述)這並不意味着要異步,那么根本不要使用回調,只需返回值的簡單函數/方法即可: http : //fiddle.jshell.net/y1m36w9p/2/

例如

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

// Create a instance of the getName class
var test = new getName();

// Get the fullname asyc and process the result
var fullname = test.name("John", "Smith");

// Do what you like with the value returned from the function
alert(fullname); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM