Saving functions within objects

I am having a bit of a head scratchy of an issue, and I'm hoping that maybe someone can assist. I'm not sure if I'm approaching this in a really stupid way or not, so please any constructive criticism is welcome.


I have created a new array called _stores that is a part of Game_System.


Intilization code is:-


Belone.Trade.Game_System_Intitalize = Game_System.prototype.initialize;
Game_System.prototype.initialize = function() {
Belone.Trade.Game_System_Intitalize.call(this);
this._stores = [];
};


I then push TradeStore objects to this array.


Within the TradeStore object are two arrays (importGoods and exportGoods). That are made up of objects (Goods - unsurprisingly).


Here is my code to add importGoods (the exportGoods is exactly the same).


this.addImport = function(item){
var newGood = {
good: item,
quantity: 0,
price: 0,
changeQuantity: function(amount){
var newQuantity = this.quantity + amount;
this.quantity = newQuantity ;
this.price = ((100 - newQuantity) * this.good.priceMultiplier).clamp(this.good.minPrice, this.good.maxPrice);
}
};
newGood.changeQuantity(0);
this.importGoods.push(newGood);
}


The issue is the changeQuantity function - this works exactly as intended on a New Game, however if I save the game and reload it then it reports the function as undefined, it can however read all other properties of the object, so the object is definitely getting saved, just not the functions within in.


I've tried creating some dummy functions and these have the same issue.


Have I done something wrong? Do I need to alter the save file operation to incorporate this functionality? Is there a better way of doing this?


Thanks in advance.
You have 2 options here:


- Create a global class (prototype) and store instances of it. The class needs to be global or JSON.parse won't recognize it, so better prefix the classname with your own or make otherwise make sure it stays unique.


- Define the class in the plugin and just don't store it. The function is generic, so there's no reason to store it in the savefile.


It's possible to serialize functions with a modified JSON object, but i strongly advise against it. JSON files are meant to contain data, not logic.
You're a super hero, thank you very much.


Changed my function into a global class and now it's working like a dream.


Guess I need to go read up on JSON some more.


Thanks again.

Original thread: https://forums.rpgmakerweb.com/threads/saving-functions-within-objects.62034/