简体   繁体   中英

How can i access this variable out side the function in javascript?

function testing() {
  var test = function() {
    console.log("hi");
  };
  return test;
}
testing.test;

this doesn't console the content of the variable test.

You can just execute the test function after executing the testing function:

 function testing() { var test = function() { console.log("hi"); }; return test; } testing()(); 

If you want to use testing like an object, you can return one:

 function testing() { var test = function() { console.log("hi"); }; return {test:test}; } testing().test(); 

There are many ways to deal with this problem, here are some of them,

Return the variable itself, and run the function,

function testing() {
  var test = function() {
    console.log("hi");
  };
  return test;
}
testing()(); // <-- weird as heck, testing() returns a function, and we execute it.

Run the function and return the variable,

function testing() {
  var test = function() {
    console.log("hi");
  };
  return test();
}
testing();

Turn it into an object,

var testing = {
  test: function(){ console.log("hi") }
}

testing.test() // <-- access the test however you want.

Return an object,

function testing() {
  return {
    test: function() {
     console.log("hi");
    };
}
testing().test // <-- this is a function, execute it as you wish

Turn it into a prototype.

function Testing(){}
Testing.prototype.test = function() {
 console.log("hi");
};
new Testing().test() // access it

You need to execute the test function

 function testing() { var test = function() { console.log("hi"); }; return test(); // changed here } testing(); 

Otherwise create an object testing & let test be a method of that object

 var testing = { test: function() { console.log("hi"); } } testing.test(); 

Your testing() function returns another function. You must assign the return value to a variable and then call that function to get the result that your looking for:

function testing() {
  var test = function() {
    console.log("hi");
  };
  return test;
}
var test = testing();
test()

//Or alternatively:
testing()();

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