2017-10-16 71 views
0

我想从ES6类访问参数没有太多成功。所以我有这个动物类需要foodLevel的第二个参数,并且我有一个叫做setHunger的函数,它每秒都会降低食物水平。获得访问ES6构造函数变量

我想访问另一个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();应该给我foodLevel数字,但我越来越没有定义。感谢帮助。

+2

好了,'setHunger'不返回任何东西。函数返回任何*显式*隐式返回'undefined' *。另一个值得怀疑的选择是'setInterval':即使函数返回一个值,'foodLevel'的值也只会在一秒后更新。但是,您似乎希望在调用该函数时立即更改该值。我想你想要的是'setHunger(){return - this.foodLevel;}'。 –

+1

如果你打算包含一个可运行的代码片段(这是一个好主意),你应该包含足够的代码。 ;-) – RobG

+0

'newAnimal.foodLevel'应该给你'10',然后再运行'setHunger()'。 'setHunger()'只是调整'AnimalInstance.foodLevel',但不返回任何东西,所以它返回'undefined'。 – PHPglue

回答

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'; 
+0

我如何从不同的js文件访问newAnimal.foodLevel?我的问题是不清楚,但animal-interface.js文件是另一个文件...这就是为什么我导入{动物} ...我试图访问newAnimal.foodLevel,它只是给了我一个错误,因为foodLevel未定义在那个文件中。 – Lucky500

+0

居然没关系,我的错误....谢谢你的答案。 – Lucky500