简体   繁体   English

Javascript function 里面一个 function 访问

[英]Javascript function inside a function access

how can I access a function inside a function?如何在 function 中访问 function? Here's an example:这是一个例子:

function fun1() {
  //some code here
  var example = function (){
    //some code here
  }
  return {
    example: example
  }
}

when i try to access it like this fun1.example() I get error fun1.example is not a function.当我尝试像这样fun1.example()访问它时,我收到错误fun1.example 不是 function。 What am I doing wrong?我究竟做错了什么?

Please look at comments for more info请查看评论以获取更多信息

function fun1() {
  //some code here
  var example = function () {
    //some code here
  };
  return {
    example: example,
  };
}
// Fun1 is funtion, In funtion there is no property like example

// So when you call fun1.example , which undefined. Is not a function
fun1.example() // Error here

const obj = fun1() // call funtion to get obj

obj.example() // No error

You have to run the code as fun().example(), or store the result of fun() into a variable and then run it, like this:您必须将代码作为 fun().example() 运行,或者将 fun() 的结果存储到变量中然后运行它,如下所示:

var fun = ();
fun.example();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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