Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
177 views
in Technique[技术] by (71.8m points)

javascript - Functions inside objects

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 :

argument1.function(argument2);

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

argument1.argument2.function(argument3);//And even more!
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Modern ES6 Approach

You no longer need to specify the function keyword when defining functions inside objects.

First option with named functions:

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

Second option with anonymous functions:

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

Pre ES6 style:

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

Note: In the first example the functions are named and have their own this-context. In the second example, the this-context from outside of the functions is used. In the third example, the functions are not named, but have their own this-context.

So while all methods seem similar, they are a bit different.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...