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 9198101
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 17, 20262026-06-17T22:12:32+00:00 2026-06-17T22:12:32+00:00

I’m starting to get my head around prototyping and closures, within Javascript, but not

  • 0

I’m starting to get my head around prototyping and closures, within Javascript, but not quite. This example below, my two objects, the second object seems to lose scope/context and takes over the first objects identity.

function broker()
{
    var _q = [];
    this.add = function(delegate) {_q[_q.length] = delegate; }
    this.broadcast = function(message)
    {
        for(qi = 0; qi < _q.length; qi++)
        {
            _q[qi](message);
        }
    }
}

function subscriber(abroker, yourname)
{
    me = this;
    this.myprop = yourname;
    this.subby = function(message){ alert(message + " " + me.myprop + me.dosomething() + secret()); };
    this.dosomething = function() {return "...abc";};
    function secret(){return "...def";}

    abroker.add(this.subby);
}

var thebroker = new broker();
var mysub = new subscriber(thebroker, 'mysub');
var myothersub = new subscriber(thebroker, 'myothersub');
thebroker.broadcast("hello from");

The idea is that there is a common broker object that can invoke a delegate on subscriber objects and execute functions within. But I’m losing scope within the invoked function called by the broker.

output: 2 alerts windows, both output: “myothersub”, mysub seems to lose scope?

I have successfully achieved the correct response by explicitly declaring the subby delegate outside of the original object, and referencing the entire object, e.g:

Instead of declaring this.subby within the subscriber object:

mysub.subby = function(message)
{
    alert(message + " " + mysub.myprop); // obv the dosomething his hidden
}

thebroker.add(mysub.subby);

Excuse me if any of the above syntax is wrong, from typing directly from memory. It does work in practice, but loses the encapsulation I’m used to.

How can I encapsulate using the original technique within out losing scope/context of the object?

  • 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-17T22:12:33+00:00Added an answer on June 17, 2026 at 10:12 pm

    SHORT ANSWER: It looks as though the problem is simply to do with your declaration of me in the subscriber constructor. At the minimum you need to put a var in front of it to make it a local/private variable for each object. So var me = this; instead of me = this;.

    EXPLANATION: In JavaScript, when you don’t explicitly declare a variable with var, it makes the variable global. So what was happening in your original script is that you created mysub which declared me as a global reference to the this inside the mysub object. But as soon as you created myothersub the global me was overwritten to the this inside the new myothersub object.

    Because your subby method created an alert that was based on me it didn’t matter which object you called it from since the method in both objects was not using anything local or specific to the object but merely referencing the same global variable — the this inside the last such object to be created

    By simply writing var me = this; instead of me = this; you create a local version of me within a closure each time for each new object you create and not one that is overwritten.

    …

    PS. Extra tip. You should do this with all variables to ensure that you have as few globals as possible, especially when you don’t mean them to be global! Therefore I’d make the same declaration for the variable qi inside the broker constructor. You could do this simply by declaring inside the loop conditions, e.g., for (var qi = 0; qi < _q.length; qi++). That would be enough to stop qi being a global variable.

    However, in the interests of keeping your code easy to read it’s best to declare all variables at the top of a function. So I would recommend simply rewriting the broadcast method thus:

    this.broadcast = function(message) {
        var qi,             // STOPS `qi` BECOMING A GLOBAL
            ql = q.length;  // SO DON'T HAVE TO CHECK LENGTH OF `q` EVERY LOOP
        for(qi = 0; qi < ql; qi += 1) {
            _q[qi](message);
        }
    };
    

    If you haven’t come across him before, Douglas Crockford is a really good go-to writer on JavaScript when it comes to closures, object creation and just good code writing conventions. There’s a bunch of tips on this page and you can find videos of him lecturing on the topic quite easily. All this really helped me when I started looking into closures and other aspects of JavaScript more closely; hope it helps you too.

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

Sidebar

Related Questions

I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
This could be a duplicate question, but I have no idea what search terms
I'm trying to convert HTML to plain text. I get many &\#8217; &\#8220; etc.
Does anyone know how can I replace this 2 symbol below from the string
I'm not entirely sure how I managed to jack this up. http://pretty-senshi.com If you
Is it possible to replace javascript w/ HTML if JavaScript is not enabled on
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
I have a .ini file as follows: [playlist] numberofentries=2 File1=http://87.230.82.17:80 Title1=(#1 - 365/1400) Example
link Im having trouble converting the html entites into html characters, (&# 8217;) i
I want to count how many characters a certain string has in PHP, but

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.