简体   繁体   中英

fetch value from another javascript

I want to pass the value(username) when scipt2 is getting called. script1 independently but after script1, so by the time script1 has the value populated but need it to be persistent to be available for future script calls.

script1.js

 var user = "";
function method1(){

    var username = document.getElementById('username').value;
    var app = new UserText();
    app.setValue(username);
    // more logic
    }
function UserText(){

    this.getValue = function(){
        return this.user;
    };

    this.setValue = function(val){
        this.user = val;
    };
}

Script2.js

alert(UserText.getValue());

You will have to expose something to the global scope. Right now, when you call method1() , the username is being stored in a specific instance of UserText . That specific instance is represented by your variable app which is currently scoped only to the method1() function.

One way to solve this is to simply move the declaration of app to the global scope. In other words, change the first part of the script to the following:

var user = "";
var app;
function method1() {
    var username = document.getElementById('username').value;
    app = new UserText();
    app.setValue(username);
    // more logic
}

Note that I have moved the var app declaration to the global scope. Now you can access the instance with your user value through

alert(app.getValue());

On a related note, you should know that your var user = ""; line does nothing at the moment, at least with the code that you have presented to us. When you are reading and writing to this.user inside your UserText class, it uses the instance of that class to store the information which is why you'll find your value inside the app.user property rather than just the user variable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM