简体   繁体   中英

Function initialization to retrieve stored value when called

I want to store an array in a Javscript function, to retrieve the value stored when called after initialized

I tried this:

function myFunc() {
  this.myArr = [];

  function init() {
    if (myArr.lenght === 0) {
      myArr.push(1);
      myArr.push(2);
      myArr.push(3);
      console.log("initialized now");
    } else {
      console.log("initialized already. Arrlength: ", myArr.lenght);
    }
  }

  return myArr;
}

myFunc.init()

console.log(myFunc());

Expected output:

initialized now
initialized already. Arrlength: 3

Obtained output:
TypeError: myFunc.init is not a function

If you didn't want to use class you always go back to the prototype method where you create a constructor function (note: class is just syntactic sugar over this prototype method and maybe easier to understand in the long-run).

 // Constructor. Set the array to null function Example() { this.arr = null; } // `init` can accept an array argument // If there is an array, set `this.arr` to it // otherwise use the default array Example.prototype.init = function(arr) { if (arr && arr.length) { this.arr = arr; return `Initialized now. length: ${this.arr.length}`; } else { this.arr = [1, 2, 3]; return `Initialized already. length: ${this.arr.length}`; } } // Not passing in an array so we use // the default array const instance = new Example(); console.log(instance.init()); // Passing in an array that gets assigned const instance2 = new Example(); console.log(instance2.init([1]));

That is because myFunc.init is invalid; myFunc is a function not an object .

You can try this:

class Something {
    constructor() {
        this.myArr = [1];
    }

    init() {
        if (this.myArr.length === 0) {
            this.myArr.push(1);
            this.myArr.push(2);
            this.myArr.push(3);
            console.log("initialized now");
        } else {
            console.log("initialized already. Arrlength: ", this.myArr.length);
        }
    }
}

new Something().init() // would give desired results.

I don't know if this is what you are trying to achieve but it's working:

function myFunc() {
  myArr = [];
  function init() {
    if (myArr.length === 0) {
      myArr.push(1);
      myArr.push(2);
      myArr.push(3);
      console.log("initialized now");
    } else {
      console.log("initialized already. Arrlength: ", myArr.length);
    }
  }
  
  function getArr() {
    return myArr;
  }
  
  myFunc.init = init;
  myFunc.getArr = getArr;
}

myFunc();
myFunc.init();
console.log(myFunc.getArr()); // output: Array(3) [ 1, 2, 3 ]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM