JavaScript: Things To Watch Out For

Kino

EIS Game Dev
Veteran
Joined
Nov 27, 2015
Messages
556
Reaction score
794
First Language
English
Primarily Uses
RMMV
JavaScript: Things To Watch Out For
Today's post isn't about new techniques. Today we cover some things to be wary of in JavaScript. These include Function Hoisting, pass by value, scoping rules, and this.



Function Hoisting
Function hosting can be a problem. When you create a function without passing it to a variable, JavaScript pushes the function to the top of your file. Here's an example:


This kind of behavior can be a cause for error if you don't understand it, because functions may be available when you don't expect them to be. If you don't want this effect, assign your functions to variables. Now since we're on functions, let's discussing scoping rules:



Scoping Rules
There three ways to declare a variable in JavaScript; you can use let, const, or var. Both let and const are block scoped; var is function scoped. This is an important distinction to make. Now, here's an example illustrating that property:


As you can see var drips out of the block scope and is available throughout the entire function; const and let do not. Furthermore, they also throw errors if used incorrectly. In most cases, let and const are preferred over var; const and let can accomplish more consistent rules when compared to var. Well, since we're on variables, let's discuss pass by value & cloning.



Pass By Value
JavaScript is a pass by value language; if you pass 2 to a variable and change it to 1, then the variable's value is 1. Well, objects and arrays are not so simple. Arrays and objects can be passed to new variables as new arrays or objects, but still, change the properties on the original. Here's an example:


Now, for me, this behavior can be confusing. See, many times JavaScript makes a shallow copy of the original array or object. This means the array of objects or list of arrays within your array refers to the same object in memory. If you're not careful, this can trip you up as a developer.

This is why you should value immutability, or when passing around objects, clone them (similar to the solution). Now, in JavaScript clone and copy are different; the clone does not reference the same object in memory -- copy does.

These are just some of the things to watch out for in JavaScript; be careful on your JavaScript coding journey. ~
 

LTN Games

Indie Studio
Veteran
Joined
Jun 25, 2015
Messages
704
Reaction score
631
First Language
English
Primarily Uses
RMMV
Object references are by far the most deceiving and #1 to watch out for. Makes you wonder why JS has never included a way to natively deep clone a function something like:
PHP:
Object.deepClone(object)[/PHP
 

Sarlecc

Veteran
Veteran
Joined
Sep 16, 2012
Messages
453
Reaction score
211
First Language
English
Primarily Uses
RMMV
Technically there are four ways to declare a variable; though the fourth really doesn't have a solid use case and should not be used as it floods the global scope. This also means that garbage collection will never free this variable as it is considered to always be in use.
Code:
function globalVariable () {
 global = 8;
 console.log(global);
};

//returns 8
globalVariable();

//also returns 8
console.log(global);
The cloning issue was/is quite prevalent in Ruby as well. I first ran into to it when creating my Time_Machine script :p.
 

Jonforum

Veteran
Veteran
Joined
Mar 28, 2016
Messages
1,623
Reaction score
1,439
First Language
French
Primarily Uses
RMMV
Pass By Value
JavaScript is a pass by value language; if you pass 2 to a variable and change it to 1, then the variable's value is 1. Well, objects and arrays are not so simple. Arrays and objects can be passed to new variables as new arrays or objects, but still, change the properties on the original.
the best fast native way i found is to use valueOf !
it will return a new valur Instead of cloning the reference.
PHP:
var pID = this._PID.valueOf(); // 5
pID++; //6
pID++; //7
console.log(this._PID); //5

// but without valueOf/////////////////
var pID = this._PID; // 5
pID++; //6
pID++; //7
console.log(this._PID); //7 !!
nativli in the core is do that
PHP:
function ObjectValueOf(){
return ToObject(this);
}
 

LTN Games

Indie Studio
Veteran
Joined
Jun 25, 2015
Messages
704
Reaction score
631
First Language
English
Primarily Uses
RMMV
This works for primitive properties only not if you have objects, arrays or functions as an object property.
PHP:
  const obj = {
    anum: 22, // works
    aString: 'Yes', // works
    anObj: {o: 1}, // Won't work
    myFunc () {} // Won't work
  }
 
  const clone = obj.valueOf()
  clone.anObj.o = 5555
  clone.myFunc = () => console.log('new function')
 
  console.log('Cloned: ', clone, 'Original: ',obj)
but you could make a function with valueOf() which recursivly goes through object applying valueOf and returns the new obejct when complete.
 

Jonforum

Veteran
Veteran
Joined
Mar 28, 2016
Messages
1,623
Reaction score
1,439
First Language
French
Primarily Uses
RMMV
This works for primitive properties only not if you have objects, arrays or functions as an object property.
but you could make a function with valueOf() which recursivly goes through object applying valueOf and returns the new obejct when complete.
I had never tested for the objects{} it is good to know;
for array i know,
In my structure, I prefer to create a direct inheritance in new bracket, [ , ] I find it cleaner and readable
example here: f46e42 inherit d8a757 valur
PHP:
//□▼↓▼□═══════════════════════════════════════════════════□□═══════════════════════════════════════════════════□↓↓↓
    _displace.prototype.iniPosition = function(position){ // 'hide' ,'default', 'custom'
        var p = this._posXY[position], X = p.base[0], Y = p.base[1];
        p.d8a757 = [X,Y]; //#d8a757 DisplaceHud BG
            p.f46e42 = [p.d8a757[0] ,p.d8a757[1]-10]; //#f46e42 TEXT STAMINA PLAY
    return p; //END
    };
//□▲↑▲□═══════════════════════════════════════════════════□□═══════════════════════════════════════════════════□↑↑↑
 

Kino

EIS Game Dev
Veteran
Joined
Nov 27, 2015
Messages
556
Reaction score
794
First Language
English
Primarily Uses
RMMV
The object bit is my main gripe, but it is manageable, but when running into more complex types, such as classes. Copying over the properties can be a bit of a pain. I'm kind of lazy so what I often do is use Object.assign for creating just about all the objects I need, but only after serializing the problem object with the JSON.parse JSON.stringify trick.

Object.assign does work in MV and can be useful if you want to enumerate all the properties on an object quickly, but to make it not a copy...well...
PHP:
function MyTest() {
  this.initialize()
}

MyTest.prototype.initialize = function() {
  this.prop = 3;
};

const test1 = new MyTest();
const test1Clone = Object.assign(new MyTest(), JSON.parse(JSON.stringify(test1))); //Breaks the link
test1Clone.prop = 5;
console.log(test1, test1Clone);
Though I think you might be able to use type coercion and change the prototype. But this is cleaner and allows you to copy over the prototype methods.
 

Mister.Right

Veteran
Veteran
Joined
Mar 7, 2015
Messages
249
Reaction score
83
Primarily Uses
Not sure RMMV supports ES6 but ES5 block scope can only be done with function immediate since let is ES6's feature.
 

Kino

EIS Game Dev
Veteran
Joined
Nov 27, 2015
Messages
556
Reaction score
794
First Language
English
Primarily Uses
RMMV
Let and const have support in RMMV but only if you use 'use strict'. The support is spotty though, but you do have generator functions, classes, template strings, and a couple of the new methods!!!
 

Jonforum

Veteran
Veteran
Joined
Mar 28, 2016
Messages
1,623
Reaction score
1,439
First Language
French
Primarily Uses
RMMV
Let and const have support in RMMV but only if you use 'use strict'. The support is spotty though, but you do have generator functions, classes, template strings, and a couple of the new methods!!!
! I didn't know , thank you for the info
 

Kino

EIS Game Dev
Veteran
Joined
Nov 27, 2015
Messages
556
Reaction score
794
First Language
English
Primarily Uses
RMMV
In MV itself there might be some loss, but most browsers support es6 currently. I wouldn't use it without a transpiler in MV though. Furthermore, use strict forces you to write good code and should help JS optimize your code.

I would only use the basic stuff like let, const, template literals to not introduce too many factors. Those make your life easy along with Object.assign
 

Mister.Right

Veteran
Veteran
Joined
Mar 7, 2015
Messages
249
Reaction score
83
Primarily Uses
Interesting, How will MV works with the browsers don't support ES6? It compiles down to ES5?
 

Kino

EIS Game Dev
Veteran
Joined
Nov 27, 2015
Messages
556
Reaction score
794
First Language
English
Primarily Uses
RMMV
In that case, I use BabelJS, but from the looks of it, a lot of browsers support es6 now. It was more of an issue a couple years ago. I think the only ones that aren't supported are certain versions of Opera (mobile version) and Internet Explorer, which was abandoned for Edge.
Here's a nice site that shows you what browsers have the support: http://caniuse.com/#

So, it really depends on how much ES6 you want to use. @Mister.Right
 

LTN Games

Indie Studio
Veteran
Joined
Jun 25, 2015
Messages
704
Reaction score
631
First Language
English
Primarily Uses
RMMV
Geez, yeah, web technology moves really quick and it's worth keeping an eye on these things because soon enough a bunch of libraries, frameworks like PIXI are going to be, or already are, written all in ES6. Almost all browsers support 98% of ES6, in fact, they're already starting to support ES2017 and beyond.
I have been writing in ES6 for the last 7 or 8months, luckily BabelJS is what allowed me to do so and have all browsers including ancient ones to be compatible with my plugins. ES6 is the not really the future anymore it's more like today's standard and almost all new tutorials from late 2016 and up are written with ES6 and I would definitely urge everyone who has not already, to learn it. Kino does a great job with his tutorials by writing both ES6 and the ES5 counterpart, so you could start there for a basic overview.
 

Mister.Right

Veteran
Veteran
Joined
Mar 7, 2015
Messages
249
Reaction score
83
Primarily Uses
Good thing to hear ES6 is becoming standard. ES5 prototype inheritance is the hard way. There still many enterprise/government projects reply on older browsers, even Angular 4 Typescript default compile to ES5.
 

Kino

EIS Game Dev
Veteran
Joined
Nov 27, 2015
Messages
556
Reaction score
794
First Language
English
Primarily Uses
RMMV
You know, I'm secretly starting to love some of the power Typescript gives us along with what it does for documentation.
http://prntscr.com/fyckwe <-- My next project.
 

Mister.Right

Veteran
Veteran
Joined
Mar 7, 2015
Messages
249
Reaction score
83
Primarily Uses
Not a fan of Typescript but it does make code easier to debug, read, in contrast, Javascript ES5 is a nightmare to work with, lacks many OOP features and flaws in design. I find only two things I like from JS are the dynamic typing and functional concept. If your background is C# or Java would take about 2 hours to learn Typescript. Typescript is cool but at the end of the day, it will be compiled to Javascript anyway.

Interface, Static type, Access modifier are 3 main things JS don't have. Module is ES6 feature, Decorator is proposed for ES7.
 

Jonforum

Veteran
Veteran
Joined
Mar 28, 2016
Messages
1,623
Reaction score
1,439
First Language
French
Primarily Uses
RMMV
I discovered recently, this super tool that allows to convert TypeScript(.TS) into Javascript(.JS)
http://www.typescriptlang.org/play/

This is very useful for reading modules because most module are written in TS
 

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

Latest Threads

Latest Posts

Latest Profile Posts

How many parameters is 'too many'??
Yay, now back in action Happy Christmas time, coming back!






Back in action to develop the indie game that has been long overdue... Final Fallacy. A game that keeps on giving! The development never ends as the developer thinks to be the smart cookie by coming back and beginning by saying... "Oh bother, this indie game has been long overdue..." How could one resist such? No-one c
So I was playing with filters and this looked interesting...

Versus the normal look...

Kind of gives a very different feel. :LZSexcite:
To whom ever person or persons who re-did the DS/DS+ asset packs for MV (as in, they are all 48x48, and not just x2 the pixel scale) .... THANK-YOU!!!!!!!!! XwwwwX

Forum statistics

Threads
105,849
Messages
1,016,977
Members
137,563
Latest member
cexojow
Top