繁体   English   中英

如何在javascript中调用函数

[英]How to call function in javascript

我正在尝试解码代码并被困在函数调用中。 函数定义如下。

 Function(){} ({ g: 0, h :{}, c:{ a:1, b:2, d:4 } });

请帮我如何调用上述函数。 如何显示 g 和访问 c 定义的变量。

我真的不知道你想要什么,但我会采取以下假设:

  1. 你的函数声明是错误的。 此处查看如何在 javascript 上声明函数;
  2. 我想你想创建一个返回给定对象的函数,然后使用它;

根据上面的猜测,遵循一个可行的代码:

 // The correct function declaration. This function returns an object. function getObject() { return { g: 0, h :{}, c:{ a:1, b:2, d:4 } }; } //The object variable will contain the result of the `getObject()` function let object = getObject(); //Prints the object to the console console.log(object); //Prints the g value to the console console.log(`g Value: ${object.g}`); //Prints the c value to the console console.log(object.c); //Prints to the console the a value that is inside of the c object console.log(`a Value inside c: ${object.ca}`);

我对你的问题的解释有两种可能的解决方案......

function test () {
    return {
        g: 0,
        h: {},
        c: {
            a:1,
            b:2,
            d:4
        }
    }
}

test().g 

0

test().c.a 

1

看起来你忘了命名你的函数,语法有点不对......

我唯一能想到的另一件事是您正在尝试获取一个附加到 Window 对象的函数。 如果是这样,您可以使用 window.Function 访问,但我不知道您为什么要这样做。

如果这不是您要找的,请告诉我。 但这就是我从阅读你的问题中得到的。 希望能帮助到你。

也许该函数应该是 IIFE(立即调用函数执行),它持有一个应该以这种方式编写的对象:

(function() {

    {
       g: 0,
       h :{},
       c:{
          a:1,
          b:2,
          d:4
         }
    }
   }())

暂无
暂无

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

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