【问题标题】:Get array in other method in the same class in javascript在javascript中的同一类中的其他方法中获取数组
【发布时间】:2020-06-18 10:26:52
【问题描述】:

我一直在这里寻找答案,但我找不到任何答案,但无论如何我的问题是如何在已在其他方法中声明和初始化但在同一个类中的方法中获取数组。我将通过展示我想要实现的目标以及到目前为止我已经尝试过的内容来更清楚地说明这一点。

Javascript:

class SomeClass {
   method1() {
      var array = new array();
      //its actually a 2d array and it is being initialised here but for simplicity this isn't 
      //necessary in the example.
   }

   method2() {
   // --> Here i want to access the array and it's contents.

   //I have tried this:
   this.array;
   //and 
   array;
   }
}

但是当我尝试 this.array 时,我得到“无法准备好未定义的属性”;

【问题讨论】:

  • 不建议使用没有构造函数的类

标签: javascript arrays class oop 2d


【解决方案1】:

您必须将数组声明为类的元素,而不是在方法内,为此,您可以使用构造函数。

在这个link你可以看到更多信息。

这是一个例子:

class SomeClass {
  constructor(someValue) {
    // Initialize array or any other atribute
    this.arr = new Array(someValue);
  }
  
   method1() {
      console.log(this.arr);
   }

   method2() {
     console.log(this.arr);
   }
}

var instance = new SomeClass('data');
instance.method1();
instance.method2();

【讨论】:

    【解决方案2】:

    好吧,你犯了一个重大错误,你的 OOP 概念正处于危险之中。 要将数组作为类的属性/实例访问,您需要在类中声明一个构造函数。有点像这个

      class SomeClass {
         constructor(){
             this.array = new Array();
         }
         yourMethod1(){
            console.log(this.array); /// You cann access it here and manipulate
         }
         yourMethod2(){
            console.log(this.array); // You can accesss here too and do the same
        }
     }
    

    稍后您可以像这样创建类的实例并访问方法并执行任何操作

      let a = new SomeClass();
      a.yourMethod1();
      a.yourMethod2();
    

    【讨论】:

      【解决方案3】:

      method1 中声明的数组仅在该函数中可用。无法在其他函数中访问函数的局部变量。

      解决方案是使用数组作为类实例的属性

      class SomeClass {
         constructor(){
          this.array = []
         }
         method1() {
            console.log(this.array);
         }
         method2() {
            console.log(this.array)
         }
      }
      
      const obj = new SomeClass();
      obj.method1();
      obj.method2();

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-04-15
        • 2021-04-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-09-16
        相关资源
        最近更新 更多