0

working on a script and I thought dot notation would be a good way of building methods to use later on in the grander scheme of the script.

the original system would declare functions written as

  • memRead();
  • memReadGlobal();
  • memWrite();
  • memEtc();.......

but I wanted to change this to

  • mem.Read();
  • mem.Read.Global();

Here is an example

var mem = {
 Read: { 
 function() {
 console.log('Hello World')
 },
 Global: 
 function(key) {
 console.log('Goodbye World')
 },
 },
}

I can call mem.Global just fine, but I can't call mem.Read

I can declare mem.Read if I add another object like Local(mem.Read.Local), but I feel like writing local is redundant and would like to avoid that.

Is there a way to create a nested function like I describe above?

asked Nov 28, 2020 at 14:53
1
  • 1
    You are trying to do something that JavaScript object initializer syntax does not allow. Commented Nov 28, 2020 at 14:56

1 Answer 1

3

You can do that, but not with an object initializer expression.

var mem = {
 Read() {
 console.log("Hello from Read");
 }
};
mem.Read.Global = function() {
 console.log("Hello from Global");
};
mem.Read();
mem.Read.Global();
answered Nov 28, 2020 at 14:59

2 Comments

Also, and this is of course merely an opinion, function names should start with a lower-case letter unless they're intended to be used as constructors.
Thanks @Pointy this worked well and I'll note to keep these functions lowercase :) Self taught and still learning. Thanks again :)

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.