Es6类变量

时间:2017-03-21 12:59:11

标签: ecmascript-6

我已经创建了这个ES6类,我正在尝试使用我在构造函数中定义的变量,但是当我在console.log this.customerTz时,它返回undefined

我也尝试将变量放在班级的顶端,但它似乎不起作用 是否有可能有变量?

class DateTimeConverter {
constructor() {
    this.format = 'YYYY-MM-DD HH:mm:ss';
    this.customerTz = 'Europe/Oslo';
}

static convertToUtc(date) {
    console.log(this.customerTz);
    // Set customer timezone
    date = moment.tz(date, this.customerTz);

    // Convert to UTC
    date = date.clone().tz('UTC');

    // Set format to something PHP thinks is valid
    date = date.format(this.format);

    return date;
}
}

4 个答案:

答案 0 :(得分:2)

convertToUtc是一种静态方法,它无法访问实例上的任何属性。相反,您可以修改如下代码



class DateTimeConverter {
    
    static convertToUtc(date) {
        console.log(DateTimeConverter.customerTz); // Static property
        
        // Set customer timezone
        date = moment.tz(date, DateTimeConverter.customerTz);
    
        // Convert to UTC
        date = date.clone().tz('UTC');
    
        // Set format to something PHP thinks is valid
        date = date.format(DateTimeConverter.format);
    
        return date;
    }
}

DateTimeConverter.format = 'YYYY-MM-DD HH:mm:ss';
DateTimeConverter.customerTz = 'Europe/Oslo';


console.log(DateTimeConverter.convertToUtc(new Date()));

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.0/moment.min.js"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.11/moment-timezone.min.js"></script>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

由于convertToUtc是一个静态方法,因此在调用convertToUtc方法时,没有DateTimeConverter类的实例this。您可以使convertToUtc不是静态方法,然后在DateTimeConverter类的实例上调用它。

答案 2 :(得分:1)

看起来你根本不需要class,因为没有理由实例化这个构造函数。相反,为模块使用普通对象文字:

const DateTimeConverter = {
    format: 'YYYY-MM-DD HH:mm:ss',
    customerTz: 'Europe/Oslo',
    convertToUtc(date) {
        console.log(this.customerTz);
        // Set customer timezone
        date = moment.tz(date, this.customerTz);

        // Convert to UTC
        date = date.clone().tz('UTC');

        // Set format to something PHP thinks is valid
        date = date.format(this.format);

        return date;
    }
};

答案 3 :(得分:0)

您的函数convertToUtc是静态的。静态函数与类本身相关联,而不与类的实例相关联。不会调用构造函数,因为您不创建实例。所以this.customerTz将不会在函数内定义。取出static

class DateTimeConverter {
  constructor() {
   this.format = 'YYYY-MM-DD HH:mm:ss';
   this.customerTz = 'Europe/Oslo';
  }

  convertToUtc(date) {
   console.log(this.customerTz);

   date = moment.tz(date, this.customerTz);

   // Convert to UTC
   date = date.clone().tz('UTC');

   // Set format to something PHP thinks is valid
   date = date.format(this.format);

   return date;
  }
}