1

I try to understand how properties works in ExtJs class. Refer to below code:

Ext.define('My.sample.Person', {
    name: 'Unknown',
    food: undefined,
    foodList: [],
    constructor: function(name) {
        if (name) {
            this.name = name;
        }
    },

    eat: function(foodType) {
        console.log(this.name + " is eating: " + foodType);
        this.food = foodType;
        this.foodList.push(foodType);
        //this.foodList = [foodType]
    },
    
    showFood:function() {
         console.log(this.name);
        console.log(this.food);
    },
    
     showFoodList:function() {
         console.log(this.name);
        console.log(this.foodList);
    }
});

var bob = Ext.create('My.sample.Person', 'Bob');
bob.eat("Salad"); 
bob.showFood(); 
bob.showFoodList(); 
console.log(bob)
var alan = Ext.create('My.sample.Person', 'alan');
console.log(alan)
alan.showFood();
alan.showFoodList(); 
<script src="https://cdnjs.cloudflare.com/ajax/libs/extjs/6.2.0/ext-all.js"></script>

If you check the result of "alan", the food = undefined and foodList = ['salad'] because somehow foodList was assigned to prototype.

enter image description here


Meanwhile, if you do like this, then it will behave normally like it should. Any idea why? What is the concept behind?

enter image description here

Result:

enter image description here

Neo
  • 141
  • 11
  • But alan has not eaten any salad yet. :) – Muzaffer Galata Oct 08 '20 at 10:24
  • haha, yeah. exactly. but this.foodList.push(foodType); will modify the prototype. it seems only array and object will do that, while string wont have this issue – Neo Oct 08 '20 at 10:30
  • You're right. Here is a good article. https://moduscreate.com/blog/a-dive-into-the-sencha-class-config-system/ – Muzaffer Galata Oct 08 '20 at 10:32
  • yeah, i saw the article before, but doesnt really solve my puzzle.. because it focus more on config while i'm not using the config .. hmm.. – Neo Oct 08 '20 at 11:39
  • 1
    This is what exactly your issue is: https://stackoverflow.com/a/42129243/1068246 – Muzaffer Galata Oct 08 '20 at 12:31
  • Thanks. Ya, i think that should answer it. only weird thing is by right, all the properties of the prototype should remain value as well. But in ExtJs, only object/array remain. Refer my example above, the "food" property get refreshed as undefined. `function MyClass(item) { this.items.push(item); } MyClass.prototype.items = []; MyClass.prototype.item = 'test'; var c1 = new MyClass(1); var c2 = new MyClass(2); console.log(c2.items); // returns an array of [1, 2] console.log(c2.item); //returns 'test'` – Neo Oct 23 '20 at 05:08

0 Answers0