2

I have a Javascript module:

const myModule = {
  foo: this.initializeFoo(),

  initializeFoo(){
    // some loops and stuff to create an array
  }
}

But I get an error: this.initializeFoo is not a function.

Is there some syntax I need to use to make this work, or is it not possible?

3 Answers 3

2

If you only intend to call it once and at the object's creation, then I would opt for a self-executing anonymous function:

const myModule = {
    foo: (function () {
        // some loops and stuff to create an array
    })()
};

Alternatively, you can use arrow syntax instead:

const myModule = {
    foo: (() => {
        // some loops and stuff to create an array
    })()
}

Example snippet:

const myModule = {
    foo: (() => {
        console.log('Processing');
        return Array.apply(null, {length: 10}).map(Number.call, Number);
    })()
};

// You can see that 'Processing' is only printed once
console.log(myModule.foo[2]);
console.log(myModule.foo[7]);

Sign up to request clarification or add additional context in comments.

Comments

1

Declare the initializeFoo() function in outside of the Object

const myModule = {
      foo : initializeFoo(),
    }
     
     function initializeFoo(){
     return 'hi';
     //or some loops and stuff to create an array
     }
    
    console.log(myModule)

2 Comments

I want the function to only run once on load, and save the output to a variable that I can access many times
You could then make it an immediately invoked function that returns a constant if it only needs to run ocne and them keep the same value.
0

If you can use ES6:

class MyModule {
  constructor() {
    this.initializeFoo();
  }
  initializeFoo() {
    console.log('test');
    // some loops and stuff to create an array
  }
}

const myModule = new MyModule();

If you need to store the result of initializeFoo():

class MyModule {
  constructor() {
    this.initializeFoo();
  }
  initializeFoo(){
    console.log('test');
    this.initialVal = 2;
  }
}

const myModule = new MyModule();
// 'test'

myModule.initialVal
// 2

Comments

Your Answer

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.