0

I am writting my first program in JS with an object "formulas" containing functions. Functions will be defined there often with other functions. All of them from "formulas" and I would like to have short, easy access to some of them (like "impl" in the example below).

Now, I manage to do it outside the "formulas", but it makes the code harder to write or read and global variables are not suggested. Could I do it somehow inside and once for each shortcut? I plan to define lambda functions there too.

    let formulas = {
        "implication": function(x,y) {

            return       !(x && !y);   
        },
        "impl": function(x,y) {return implication(x,y);}, 
          //a short cut to formulas.implication(x,y) also didn't worked
        "non_causality": function(x,y) {

            return  impl(x,y) === impl(y,x);
        }
    };
undefined
formulas.non_causality(true, false);

VM32648:9 Uncaught ReferenceError: impl is not defined
    at Object.non_causality (<anonymous>:9:4)
    at <anonymous>:1:10
non_causality @ VM32648:9
(anonymous) @ VM32656:1

    let formulas = {
        "implication": function(x,y) {

            return       !(x && !y);   
        },
        "non_causality": function(x,y) {

            return  formulas.implication(x,y) === formulas.implication(y,x);
        }
    };
//undefined
formulas.non_causality(true, false);
//false  - This one worked,
//: ] a shortcut "impl" would be helpful though.
szai
  • 13
  • 5
  • 3
    You have to explicitly write `this.impl`, not just `impl` – Pointy May 10 '20 at 20:19
  • See also https://stackoverflow.com/questions/10711064/javascript-object-literal-reference-in-own-keys-function-instead-of-this – Bergi May 10 '20 at 21:56
  • If you want `impl` as a shortcut, you have do declare a variable with that name, not just create an object method. `const impl = this.implication; return impl(x,y) === impl(y,x);` would work for example – Bergi May 10 '20 at 21:57
  • Yes, I plan to fix the ```obj``` with a ```const```, when I am done with the draft. ```this``` works, but seems to be problematic on a longer run. Resilience seems a good feature. Thank You! – szai May 11 '20 at 11:50

0 Answers0