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?
-
1You are trying to do something that JavaScript object initializer syntax does not allow.Pointy– Pointy2020年11月28日 14:56:27 +00:00Commented Nov 28, 2020 at 14:56
1 Answer 1
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();