Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8771645
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 13, 20262026-06-13T17:50:34+00:00 2026-06-13T17:50:34+00:00

Background : I want to rewrite a library (which I did not write) to

  • 0

Background: I want to rewrite a library (which I did not write) to avoid having the Closure Compiler generate warnings with the advanced option. Per this question JavaScript “this” keyword and Closure Compiler warnings the answer was to rewrite the code using a closure. The intent is to avoid using the keyword this (which generates the compiler warnings).

As the library has a number of functions, I though it would be best for the new closure to return an object literal. I want to understand how this works and any possible ramifications. I therefore wrote the following (meaningless) example as a learning expercise (also here: jsFiddle):

  var CurrencyObject = function(Amount) {
        var money = Amount;
        return {
              "toCents": function() {
                    money *= 100;
                    return money;
              },
              "toDollars": function() {
                    money /= 100;
                    return money;
              },
              "currentValue": money  // currentValue is always value of Amount
        };
  }; // end currencyObject

  var c1 = CurrencyObject(1.99); // what's the difference if the syntax includes `new`?

  alert('cents = ' + c1.toCents() + '\ncurrent money = ' + c1.currentValue + '\ndollars = ' + c1.toDollars() + '\ncurrent money = ' + c1.currentValue);

  var c2 = CurrencyObject(2.99);

  alert('cents = ' + c2.toCents() + '\ncurrent money = ' + c2.currentValue + '\ndollars = ' + c2.toDollars() + '\ncurrent money = ' + c2.currentValue);

  alert('cents = ' + c1.toCents() + '\ncurrent money = ' + c1.currentValue + '\ndollars = ' + c1.makeDollars() + '\ncurrent money = ' + c1.currentValue);

Q1: Why isn’t currentValue updated after the call to toCents? (I’m going to guess that it is because currentValue is a literal(?) that it is initialized when CurrencyObject is first executed. If that’s the case, what’s the syntax for also returning the property currentValue?)

Q2: This syntax (with new) var c1 = new CurrencyObject(1.99); does not change the code’s behavior in a way that I can detect, yet I assume there is a difference. What is it?

Q3: When c2 is instantiated, are copies of the functions being created or will c1 and c2 share the same (function) code? (If copies of the functions are being created, what changes do I make to avoid that?)

TIA

BTW: In the event someone is wondering, the symbols in the object literal are quoted to avoid having the Closure-Compiler rename them.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-13T17:50:35+00:00Added an answer on June 13, 2026 at 5:50 pm

    UPDATE:
    I branched your fiddle, and added a couple of methods that all instances will in fact share (ie: no new function objects will be created for each instance): the methods that convert the amount into Euro’s or Pounds, for example. I’ve also omitted the money variable, because it’s simply not necessary. To avoid having to use this as much as possible, I’ve also assigned the returned object to a variable within the closure scope, so that all methods can reference their parent object via that variable name, rather than having to rely on this.
    Shared methods, however, will still have to use this occasionally, because they were declared in a “higher” scope, and don’t have access to the returnObject variable, simply because it doesn’t exist in their scope. Lifting the returnObject variable declaration is no solution in case you were wondering, because then you’ll soon find out that you can’t create more than 1 instance of the currency object.
    Lastly, I’ve changed the name of the “constructor” to start with a lower case. Technically, your function is not a constructor any longer, and convention is that it therefore can’t start with an upper-case letter… Let me know if anything I explained here, or any of my suggested changes are still unclear to you.

    The currentValue isn’t updated because you changed the money variable’s value by doing: money *= 100;. This statement multiplies the money value and assigns it to the same variable. Since this is a primitive, currentValue has its own copy of this value, they’re not linked in any way.
    Suggestions: use return money/100; to keep the value of money constant. As it now stands calling the toCents method twice is the same as multiplying the original amount by 10,000. To update/set the currentValue on each call to whatever you want it to be, add: this.currentValue = money*100;, which is a little dangerous, or giving your closure access to its own literal by using a named reference (which is safer, but a bit more verbose):

    var someClosure = function (amount)
    {
        var money = amount;//redundant: you can use amount, it's preserved in this scope, too
        var me = {currentValue:amount,
                  toCents: function()
                  {
                      me.currentValue = money*100;//<-- use me to refer to the object itself
                      return amount/100;
                  }
          };
          return me;
    }
    

    There is no reason to use the new keyword: the object that is created by this “constructor” is an object literal, it has only 1 prototype (Object.prototype, and no explicit constructor name). Adding new will make this point to a new object in the function itself, but since you’re not using it, and your function returns another object, the object is never returend.

    Strictly speaking: some JS engines will create new function objects for each new instance. Some modern objects optimize this, and will in fact only create 1 function object. To be on the safe side, you can wrap another closure around things, to make sure there is only 1 function, regardless of what engine runs your code:

    var someObjectGenerator = (function()
    {
        var oneOffFunction = function()
        {
            console.log('this function will only be created once');
        }
        return function(amount)
        {
            return {    foo:oneOffFunction,
                        toCents: function()
                        {
                            return amoutn/100;
                        }
                    };
        };
    };
    

    Of course, functions that are created in a scope above the one that has the money or amount variable won’t have access to that variable, so in that case you’ll have to create new functions… but JS objects are very cheap, so don’t worry about it that much.
    Again, most engines deal with this rather well.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Background : I want to create a custom VB compiler, extending the original compiler,
I am developing a small app in which I want a background service to
Background: I want to define few static methods in C# , and generate IL
Background: I want to check-out the source code from Cliche , which is stored
Background: I want to avoid creating an Alternate Layout for my home-page and I'd
Background: I want to add a login to my small site, which is an
Background I want to access the cache of Chrome and Firefox in my Cocoa
Background We want to run an FTP server on a Red Hat Enterprise OS.
Background: I want to show the time and date uptill only 1 week. After
I am from PHP background and want to give path to STATICFILES_DIRS in settings.py

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.