获取对ES6构造函数变量的访问权限

时间:2017-10-16 23:46:35

标签: javascript ecmascript-6

我正在尝试从ES6类访问参数而没有太大成功。所以我有这个Animal类,它接受了foodLevel的第二个参数,我有一个名为setHunger的函数,它每秒都会降低食物水平。

我正在尝试访问另一个js文件中的foodLevel,但我不确定为什么我无法获取它。在我看来,我需要调用setHunger函数来获取该数字......



//Animal.js file

export class Animal {
  constructor(name, foodLevel){
    this.name = name;
    this.foodLevel = 10;
  }

  setHunger(foodLevel){
    setInterval(() => {
      this.foodLevel--;
    }, 1000);
  }

};

//Animal interface file

import { Animal } from './../js/animal.js';

$(document).ready(function() {
    
  $('.name').on('click', function(){
    let animalName = $('.animal').val();
    let newAnimal = new Animal(animalName);
    
    var foodLevelOut = newAnimal.setHunger();
    console.log('initial', newAnimal);
     console.log('food', foodLevelOut);
    //debugger;
    //let initialFoodLevel = 10;
    //foodLevelOut = newAnimal.setHunger();

    console.log('foodLevel: 2', foodLevelOut);
  });

  $('.health').click(function() {

  });

});




所以,在我看来var foodLevelOut = newAnimal.setHunger();应该给我foodquvel数字,但我没有定义。感谢帮助。

1 个答案:

答案 0 :(得分:1)

函数setHunger()不返回值。要访问foodLevel,您需要从类中读取该属性。

jQuery已从代码段中删除以进行演示。

//Animal.js file

 class Animal {
  constructor(name, foodLevel){
    this.name = name;
    this.foodLevel = 10;
  }

  setHunger(foodLevel){
    setInterval(() => {
      this.foodLevel--;
    }, 1000);
  }

};


    let animalName = 'bob';
    let newAnimal = new Animal(animalName);
    
    newAnimal.setHunger();
    
    // The foodlevel is accessed by reading the foodLevel 
    // property of the instantiated Animal class
    console.log('food', newAnimal.foodLevel);
 
    // After 1500 seconds, the foodlevel will have decreased 
    // from the interval in the setHunger() method
    setTimeout(function() {
        console.log('foodLevel: 2', newAnimal.foodLevel);
    }, 1500)
    

如果要从其他文件访问实例,则需要导出实例化。

class Animal {
    constructor(name) {
        this.name = name;
    }
}

// Export the class instance
export const animal = new Animal('fred');

在您要访问属性的单独文件中:

import {animal} from 'Animal.js';
// animal.name == 'fred';