Javascript 对象内部的函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10378341/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 01:05:28  来源:igfitidea点击:

Functions inside objects

javascriptobject

提问by user1365010

I know the title is vague but I didn't know what to write.
In javascript, I know how to write functions that will be called like this :

我知道标题很模糊,但我不知道该写什么。
在 javascript 中,我知道如何编写将这样调用的函数:

argument1.function(argument2);

Here is the fiddle demonstration : http://jsfiddle.net/rFXhf/
Now I wonder if I can do :

这是小提琴演示:http: //jsfiddle.net/rFXhf/
现在我想知道我是否可以做到:

argument1.argument2.function(argument3);//And even more!

回答by Taha Paksu

you need to define the objects like this :

您需要像这样定义对象:

var argument1 = {
    myvar : "12",
    mymethod : function(test) { return something; }
}

then call mymethod like:

然后像这样调用 mymethod:

argument1.mymethod(parameter);

or the deeper version :

或更深的版本:

var argument1 = {
    argument2 : {
       mymethod : function(test) { return something; }
    }
} 

then:

然后:

argument1.argument2.mymethod(parameter);

回答by Govind Rai

Modern ES6 Approach

现代 ES6 方法

You no longer need to specify the functionkeyword when defining functions inside objects:

function在对象内部定义函数时不再需要指定关键字:

var myObj = {
  myMethod(params) {
    // ...do something here
  },
  myOtherMethod(params) {
    // ...do something here
  },
  nestedObj: {
    myNestedMethod(params) {
      // ...do something here
    }
  }
};

Equivalent except repetitive and verbose:

除重复和冗长外,等效:

var myObj = {
  myMethod: function myMethod(params) {
    // ...do something here
  },
  myOtherMethod: function myOtherMethod(params) {
    // ...do something here
  },
  nestedObj: {
    myNestedMethod: function myNestedMethod(params) {
      // ...do something here
    }
  }
};