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

  • Home
  • SEARCH
  • 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 4610978
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 22, 20262026-05-22T01:12:22+00:00 2026-05-22T01:12:22+00:00

I’ve managed to avoid using namespace in most of my javascript dev to date,

  • 0

I’ve managed to avoid using namespace in most of my javascript dev to date, but I’m beginning to see the light through reading helpful articles like this one

I’m following Maeagers technique found here to create my namespace as shown below –

var newAndImproved = {

//div to put loaded content into
targetDiv: "",

//loads the initial content based on an anchor tag having a class named 'chosen'
loadInitialPage: function() {
    var chosenLink = $("#subnavigation a.chosen");
    newAndImproved.loadPartial(chosenLink);
},

loadPartial: function(clickedLink) {
    var theUrlToLoad = $(clickedLink).attr("href");
    $(newAndImproved.targetDiv).load(theUrlToLoad, function(response, status, xhr) {
        if (status == "error") {
            var msg = "Sorry but there was an error: ";
            $(targetDiv).html(msg);
        }
    });
},

removeClassFromSubNav: function() {
    $("#subnavigation a").removeClass('chosen');
},

addChosenClassToNav: function(chosenLink) {
    $(chosenLink).addClass('chosen');
},

bindMethodsToNavigation: function() {
    $("#subnavigation a").bind('click', function(event) {
        var chosenLink = event.target;
        newAndImproved.removeClassFromSubNav();
        newAndImproved.loadPartial(chosenLink);
        newAndImproved.addChosenClassToNav(chosenLink);
        return false;
    });
}

};

I’ve called that namespace like this –

$(document).ready(function() {
newAndImproved.targetDiv = $("#subcontent");
newAndImproved.loadInitialPage();
newAndImproved.bindMethodsToNavigation();
});

I’m sure you’ve noticed that I’m referencing the namespace within itself rather than just using ‘this’. I assume this is incorrect. But when I use ‘this’ the binding part will not work.

Strangely, the loadInitialPage method will work when using ‘this’.

Any idea what I’m doing wrong?

Thanks in advance.

  • 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-05-22T01:12:23+00:00Added an answer on May 22, 2026 at 1:12 am

    You need to use the that trick. this gets re-assigned inside new scopes, including the anonymous function you are binding.

    Consider this code:

    function say(x){ alert(x); }
    
    var myscope = {
    
        label : "myscope (toplevel)",
    
        func1 : function() {
            say("enter func1");
            var label = "inner func1";
            say("  this.label: " + this.label);
            say("  label: " + label);
        },
    
        func2 : function() {
            var label = "inner func2";
            say("enter func2");
            this.func1();
        }
    };
    
    myscope.func2();
    

    If you run this, it will behave nicely, and the references to this.xxx all succeed as you would like. However, if you add a func3 like this:

        func3 : function() {
            setTimeout( function(){
                var label = "anonymous func";
                say("enter anon func");
                this.func1();
            }, 2);
        }
    

    …it will not work as you might imagine. Because the anonymous function is defined in no explicitly-specified scope, the this within it refers to the top level object, window. And there is no func1 as a child of window (no top level object named func1).

    For the same reason, the this within your anon function that you use in the call to bind() will fail. In that case you can refer to the “namespace” object directly, or you can use a closure (some people call it “the that trick”):

        bindMethodsToNavigation: function() {
            var that = this;
            $("#subnavigation a").bind('click', function(event) {
                var chosenLink = event.target;
                that.removeClassFromSubNav();
                that.loadPartial(chosenLink);
                that.addChosenClassToNav(chosenLink);
                return false;
            });
        }
    

    The this within the scope of bindMethodsToNavigation refers to newAndImproved. The this within the anonymous function will refer to window. Using a closure allows you to refer to the thing you want. (editorial comment: I personally find the name that to be cute and entirely unhelpful. I like to use abbreviated names, in your case maybe something like nai to refer to newAndImproved)

    Incidentally, you could also do this:

        clickHandler : function(event) {
            var chosenLink = event.target;
            this.removeClassFromSubNav();
            this.loadPartial(chosenLink);
            this.addChosenClassToNav(chosenLink);
            return false;
        },
    
        bindMethodsToNavigation: function() {
            $("#subnavigation a").bind('click', clickHandler);
        },
    

    …and if they are both members of the newAndImproved object, then the this within clickHandler will be resolved to the newAndImproved object. The key here is that clickHandler is not an anonymous, top-level function; it belongs to newAndImproved and when this is used within it, it resolves appropriately. Even more, you can just drop the use of this within clickHandler; it is not incorrect, but it is unnecessary. Some people like to add it for emphasis to those who might read the code later.


    EDIT

    One more note on this – on the decision whether to use anonymous functions or named functions as event handlers… Anon functions are so convenient and easy, and everybody uses them. What I find is that in Firebug or the IE Javascript Debugger, when I look at a stack trace I get a loooong list of anon functions, and it’s difficult to figure out just what the chain of functions is. Especially with AJAX and async handlers being fired in response to UI events, and so on. To provide some additional visibility at debug time, I sometimes use named functions (put into namespaces), and the callstack will show a few named fns along interspersed with a few anon fns. This sometimes helps.
    Just a small thing, though.

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

Sidebar

Related Questions

link Im having trouble converting the html entites into html characters, (&# 8217;) i
That's pretty much it. I'm using Nokogiri to scrape a web page what has
I want to count how many characters a certain string has in PHP, but
I am trying to loop through a bunch of documents I have to put
I'm making a simple page using Google Maps API 3. My first. One marker
I used javascript for loading a picture on my website depending on which small
Seemingly simple, but I cannot find anything relevant on the web. What is the
I have a French site that I want to parse, but am running into
I'm using v2.0 of ClassTextile.php, with the following call: $testimonial_text = $textile->TextileRestricted($_POST['testimonial']); ... and
I'm parsing an RSS feed that has an ’ in it. SimpleXML turns this

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.