Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to give a specific context to a JavaScript function without invoking it right away
    primarykey
    data
    text
    <p>I'd like to create an object with some hidden (using closures) variables, and methods that utilize those hidden variables. I don't however want to recreate those methods for each instantiation. I'd like to have them in memory once. I'm using plain functions to instantiate objects.</p> <p>Here's some code:</p> <pre><code>function Mario () { var mario = {}; // create the obj mario.name = "Mario"; // create a property on it mario.hp = (function () { // set up a closure var currentHp = Mario.baseHp * 100; // create a "hidden" variable return function (value) { // return the hp function that utilizes the hidden currentHp variable if (!!value) { return currentHp = ((currentHp * Mario.baseHp) + value); } return currentHp * Mario.baseHp; }; }()); return mario; // send along the newly created object } Mario.baseHp = 1; var mario = Mario(); log(mario); log(mario.hp()); log(mario.hp(-20)); log(mario.hp()); </code></pre> <p>The problem here is that every time I create another "mario" object, I've created the hp function again in memory. Here's my attempt at a solution so far:</p> <pre><code>function Mario () { var mario = {}; // create the obj mario.name = "Mario"; // create a property on it mario.hp = (function () { // set up a closure var currentHp = Mario.baseHp * 100; // create a "hidden" variable return Mario.hp; // reference the hp function below..... but the context is wrong, it needs access to currentHp variable. }()); return mario; // send along the newly created object. } Mario.baseHp = 1; Mario.hp = function (value) { // Create the hp function once in memory if (!!value) { return currentHp = ((currentHp * Mario.baseHp) + value); } return currentHp * Mario.baseHp; }; var mario = Mario(); log(mario); log(mario.hp()); log(mario.hp(-20)); log(mario.hp()); </code></pre> <p>But obviously the context of Mario.hp is wrong. I'm thinking there might be a way to use call or apply that would resolve this. Any help would rock!</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload