简体   繁体   中英

How do I access an array that is called from inside a function outside of an object in JavaScript

I'm working with ES 6 and I have a an array assigned to an object like so.

let myArray = [];

further down in my object I have aa function assigned to a handler like so.

myFunction: doSomething

Now outside of the object I define the function.

const doSomething = function(arg){}

So my problem is that when I try to assign something to the array inside of this outer function JavaScript has no idea what that thing is.

I can't figure out how to access this global array inside of the object. So when I to assign a value to this array I get an error.

class myObject {
   var myArray = [],
   myFunction: doSomething,
}

const doSomething = function(arg) {
    let selected = $.map(this.select(), (item) => {
        this.myArray[this.dataItem(item).Id] = true;
    });
}

What you have shown for class myObject is not valid syntax.

You can't declare a variable such as var myArray = [] in a class declaration like that. Similarly, myFunction: doSomething, is not correct either. See the proper ES6 class syntax here on MDN .

If you want to initialize a property on the object, then you can do that inside the constructor with this.myArray = [] and then you can access this.myArray inside any method. Here's is some valid syntax:

class myObject {
   constructor() {
       this.myArray = [];
   }

   myFunction(arg) {
       let selected = $.map(this.select(), (item) => {
           this.myArray[this.dataItem(item).Id] = true;
       });
   }
}

Then, you would use it as:

var x = new myObject();
x.myFunction();

I also notice that the method myFunction assumes there are other methods dataItem() and select() so you would have to define those methods too for this code to work.

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