簡體   English   中英

訪問ES6構造函數變量

[英]getting access to ES6 constructor variable

我正在嘗試從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(); 應該讓我得到foodLevel編號,但是我變得不確定。 感謝您的幫助。

函數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';

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM