簡體   English   中英

如何在javascript函數之外訪問此變量?

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

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

這不能控制變量test的內容。

您可以在執行測試功能后執行測試功能:

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

如果要像對象一樣使用testing ,則可以返回一個:

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

有很多方法可以解決此問題,以下是其中一些方法,

返回變量本身,然后運行函數,

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

運行函數並返回變量,

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

把它變成一個物體,

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

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

返回一個對象,

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

將其變成原型。

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

您需要執行test功能

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

否則,創建一個對象testing並讓test作為該對象的方法

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

您的testing()函數返回另一個函數。 您必須將返回值分配給變量,然后調用該函數以獲得所需的結果:

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

//Or alternatively:
testing()();

暫無
暫無

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

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