Classes and methods in Rpg_Core.js

Status
Not open for further replies.

Eliaquim

Raze: The Rakuen Zero's Guardian!
Veteran
Joined
May 22, 2018
Messages
1,076
Reaction score
447
First Language
Portuguese - Br
Primarily Uses
RMMV
Hi people!

Well, I'm studying JavaScript and I'm learning about classes in ES6 syntax.
That would be something like that, right?

JavaScript:
class Pessoa {
  constructor (nome, cpf) {
    this.nome = nome
    this.cpf = cpf
  }

  getNome () {
    return this.nome
  }

  getCpf () {
    return this.cpf
  }
}

But I saw in rpg_core.js that the classes are made in a different way(ES5 syntax, right?)
JavaScript:
/**
/**
* The resource class. Allows to be collected as a garbage if not use for some time or ticks
*
* @class CacheEntry
* @constructor
* @param {ResourceManager} resource manager
* @param {string} key, url of the resource
* @param {string} item - Bitmap, HTML5Audio, WebAudio - whatever you want to store in the cache
*/
function CacheEntry(cache, key, item) {
    this.cache = cache;
    this.key = key;
    this.item = item;
    this.cached = false;
    this.touchTicks = 0;
    this.touchSeconds = 0;
    this.ttlTicks = 0;
    this.ttlSeconds = 0;
    this.freedByTTL = false;
}
/**
* frees the resource
*/
CacheEntry.prototype.free = function (byTTL) {
    this.freedByTTL = byTTL || false;
    if (this.cached) {
        this.cached = false;
        delete this.cache._inner[this.key];
    }
};

}

So if I want to code this with the es6 syntax, I have to do something like this?
JavaScript:
/**
* The resource class. Allows to be collected as a garbage if not use for some time or ticks
*
* @class CacheEntry
* @constructor
* @param {ResourceManager} resource manager
* @param {string} key, url of the resource
* @param {string} item - Bitmap, HTML5Audio, WebAudio - whatever you want to store in the cache
*/

class CacheEntry{
     constructor(cache, key, item){
        this.cache = cache;
        this.key = key;
        this.item = item;
        this.cached = false;
        this.touchTicks = 0;
        this.touchSeconds = 0;
        this.ttlTicks = 0;
        this.ttlSeconds = 0;
        this.freedByTTL = false;
     }
    /**
    * frees the resource
    */
     CacheEntry(byTTL){
        this.freedByTTL = byTTL || false;
        if (this.cached) {
            this.cached = false;
            delete this.cache._inner[this.key];
        }
     }
}

Also, there are some methods in rpg core, like this one:
JavaScript:
//-----------------------------------------------------------------------------
/**
* This is not a class, but contains some methods that will be added to the
* standard Javascript objects.
*
* @class JsExtensions
*/
function JsExtensions() {
    throw new Error('This is not a class');
}

/**
* Returns a number whose value is limited to the given range.
*
* @method Number.prototype.clamp
* @param {Number} min The lower boundary
* @param {Number} max The upper boundary
* @return {Number} A number in the range (min, max)
*/
Number.prototype.clamp = function(min, max) {
    return Math.min(Math.max(this, min), max);
};

Why they used a prototype here? The Number is part of the class Js Extensions?
Or there is a class for Numbers that I don't see?
Because, in my knowledge, a prototype is used for a function to allow it being used by other classes, right(inheritance)?

I have understood this prototype:
JavaScript:
CacheEntry.prototype.free
Because I can see that is inside the class of Cache Entry.

But what about Number?

What i'm missing?

[[[EDIT]]]

Well according to this:
https://www.w3schools.com/js/js_object_prototypes.asp

It seems that "Number" is an object inherit from Object.prototype like array object, date object etc?

And in this method of RPG core that I listed above:
Number.prototype.clamp The clamp is a new property of the Number that has been added.
So, in this case, it is modifying a standard javascript object(Number) adding a new property? That's what happening?
 
Last edited:

OcRam

Servant of the Universe
Veteran
Joined
Aug 2, 2016
Messages
427
Reaction score
526
First Language
Finnish
Primarily Uses
RMMV
clamp is a new method/function to the Number object.

And then clamp method can be used with any Number object like:
parseInt(200 * Math.random()).clamp(50, 100); // will ensure that number is between 50 and 100
 

Jonforum

Veteran
Veteran
Joined
Mar 28, 2016
Messages
1,612
Reaction score
1,407
First Language
French
Primarily Uses
RMMV
you can extend the vanilla javascript without issue.
Example on my side , short list, because is huge

JavaScript:
//#STRING
String.prototype.contains = function(value) {
    return this.indexOf(value) >= 0;
};
Object.defineProperty(String.prototype, 'contains',{enumerable:false})

String.prototype.hashCode = function() {
    var hash = 0, i, chr;
    if (this.length === 0) return hash;
    for (i = 0; i < this.length; i++) {
    chr   = this.charCodeAt(i);
    hash  = ((hash << 5) - hash) + chr;
    hash |= 0; // Convert to 32bit integer
    }
    return hash;
}
Object.defineProperty(String.prototype, 'hashCode',{enumerable:false})


//#ARRAY
Array.prototype.unique = function () {
    return this.filter((v, i, s) =>  {
        return s.indexOf(v) === i;
        });
}
Object.defineProperty(Array.prototype, 'unique',{enumerable:false});

Array.prototype.count = function (value) {
    let count = 0;
    for (let i=0, l=this.length; i<l; i++) {
        this[i] === value && (count+=1);
    };
    return count;
}
Object.defineProperty(Array.prototype, 'count',{enumerable:false});


Array.prototype.equals = function (other, callback = (x, y) => (x === y)) {
    // Check the other object is of the same type
    if (this.length === other.length) {
        return this.every((x, i) => callback(x, other[i]));
    }
    return false;
   
}
Object.defineProperty(Array.prototype, 'equals',{enumerable:false})


Array.prototype.contains = function (element) {
    return this.indexOf(element) >= 0;
}
Object.defineProperty(Array.prototype, 'contains',{enumerable:false})

Array.prototype.remove = function () {
    let what;
    let a = arguments;
    let L = a.length
    let ax;
    while (L && this.length) {
        what = a[--L];
        while ((ax = this.indexOf(what)) !== -1) {
            this.splice(ax, 1);
        }
    };
    return this;
}
Object.defineProperty(Array.prototype, 'remove',{enumerable:false})

Array.prototype.findEmptyIndex = function() {
    for (let i=0, l=this.length+1; i<l; i++) {
        if(!this[i]){return i};
    };
}
Object.defineProperty(Array.prototype, 'findEmptyIndex',{enumerable:false})

Array.prototype.sum = function() {
    let value = Number.isInteger(this[0])?0:"";
    for (let i=0, l=this.length; i<l; i++) {
        value+=this[i]||0;
    };
    return value;
}
Object.defineProperty(Array.prototype, 'sum',{enumerable:false})


Array.prototype.chunk = function(howMany) {
    let chunkarr = [],
    i = 0,
    n = this.length;

    while (i < n) {
    chunkarr.push(this.slice(i, i += howMany));
    }

    return chunkarr;
}
Object.defineProperty(Array.prototype, 'chunk',{enumerable:false})

//#MATH
Math.randomFrom = function(min=0,max=1,precision=0){  
    const ranNeg = min<0? (min*=-1) && this.random() >= 0.5 && 1 || -1  : 1;
    return precision? parseFloat(Math.min(min + (Math.random() * (max - min)),max).toFixed(precision))*ranNeg : ~~(Math.random()*(max-min+1)+min)*ranNeg;
}
Object.defineProperty(Math, 'randomFrom',{enumerable:false})
And yes rmmv was in es5 syntax, but is better to use if you can es6 class, it more readable and same performance.
This is whats is look.

JavaScript:
class Class extends SuperClass{
    static staticNumber = 1;
    static staticObj = {};
    static staticAnonymFunc = function name(params) {};
    static staticScopedFunc = (params)=>{};
    constructor(params) {
        super(params); // rquired if you use extends class
    }
    method() {

    }
    get getter() {
       return this.constructor.name;
    }
};
 

Jonforum

Veteran
Veteran
Joined
Mar 28, 2016
Messages
1,612
Reaction score
1,407
First Language
French
Primarily Uses
RMMV
also since the 11 feb. 2020
Js have released somes very awesomes updates with new operators .
It named Nullish coalescing
I suggest to all people to learn this new syntax for conditional.
I also made some bench to test performances and it same so no worry to use.
Work 100% fine in V8 engine, so also in rmmv with nwjs chromium update.

Take a look, it really crazy stuff.

I made 2 bench here (you need chrome update) not yet for edge or mozilla.
Compare performance vs nullish vs, Ternary vs Logical operators.
https://jsbench.me/9ik6kmpzh0/1
https://jsbench.me/kck6knyjmg/1

juste warning if your dev for the web and not a desktop game.
1581905707552.png
 
Last edited:

MushroomCake28

KAMO Studio
Global Mod
Joined
Nov 18, 2015
Messages
2,617
Reaction score
3,790
First Language
English
Primarily Uses
RMMV
Jonforum's posts probably are the best explanations you can get.

@Jonforum Love your answers, but please avoid double posting in the future. You can simply edit your posts to add any missing information.

Double post is not allowed.

 

slimmmeiske2

Little Red Riding Hood
Global Mod
Joined
Sep 6, 2012
Messages
6,183
Reaction score
4,301
First Language
Dutch
Primarily Uses
RMXP

This thread is being closed, due to being solved. If for some reason you would like this thread re-opened, please report this post and leave a message why. Thank you.

 
Status
Not open for further replies.

Users Who Are Viewing This Thread (Users: 0, Guests: 1)

Latest Threads

Latest Posts

Latest Profile Posts

Making it a rule that I don't do any world building for my new game before the actual gameplay is concrete and working. I have 16 years of lore to work with anyway.
Cheesy power metal makes everything better. No matter what you do, you'll feel heroic doing it.
Starting to really like the first of my madness areas. I think the eyes looking at them really helps to sell the place. :LZSexcite:
Made idle animation for character. It first had only three frames but looked too different from walking animation and I had to draw five more.
MV and VX Ace both have good qualities.

Forum statistics

Threads
95,694
Messages
931,076
Members
126,034
Latest member
SuperSuck64
Top