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

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 14, 20262026-06-14T11:24:55+00:00 2026-06-14T11:24:55+00:00

In C++, the language I’m most comfortable with, usually one declares an object like

  • 0

In C++, the language I’m most comfortable with, usually one declares an object like this:

class foo
{
public:
    int bar;
    int getBar() { return bar; }
}

Calling getBar() works fine (ignoring the fact that bar might be uninitialized). The variable bar within getBar() is in the scope of class foo, so I don’t need to say this->bar unless I really need to make it clear that I’m referring to the class’ bar instead of, say, a parameter.

Now, I’m trying to get started with OOP in Javascript. So, I look up how to define classes and try the same sort of thing:

function foo()
{
     this.bar = 0;
     this.getBar = function() { return bar; }
}

And it gives me bar is undefined. Changing the bar to this.bar fixes the issue, but doing that for every variable clutters up my code quite a bit. Is this necessary for every variable? Since I can’t find any questions relating to this, it makes me feel like I’m doing something fundamentally wrong.


EDIT: Right, so, from the comments what I’m getting is that this.bar, a property of an object, references something different than bar, a local variable. Can someone say why exactly this is, in terms of scoping and objects, and if there’s another way to define an object where this isn’t necessary?

  • 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-14T11:24:56+00:00Added an answer on June 14, 2026 at 11:24 am

    JavaScript has no classes class-based object model. It uses the mightier prototypical inheritance, which can mimic classes, but is not suited well for it. Everything is an object, and objects [can] inherit from other objects.

    A constructor is just a function that assigns properties to newly created objects. The object (created by a call with the new keyword) can be referenced trough the this keyword (which is local to the function).

    A method also is just a function which is called on an object – again with this pointing to the object. At least when that function is invoked as a property of the object, using a member operator (dot, brackets). This causes lots of confusion to newbies, because if you pass around that function (e.g. to an event listener) it is “detached” from the object it was accessed on.

    Now where is the inheritance? Instances of a “class” inherit from the same prototype object. Methods are defined as function properties on that object (instead of one function for each instance), the instance on which you call them just inherits that property.

    Example:

    function Foo() {
        this.bar = "foo"; // creating a property on the instance
    }
    Foo.prototype.foo = 0; // of course you also can define other values to inherit
    Foo.prototype.getBar = function() {
        // quite useless
        return this.bar;
    }
    
    var foo = new Foo; // creates an object which inherits from Foo.prototype,
                       // applies the Foo constructor on it and assigns it to the var
    foo.getBar(); // "foo" - the inherited function is applied on the object and
                  // returns its "bar" property
    foo.bar; // "foo" - we could have done this easier.
    foo[foo.bar]; // 0 - access the "foo" property, which is inherited
    foo.foo = 1;  // and now overwrite it by creating an own property of foo
    foo[foo.getBar()]; // 1 - gets the overwritten property value. Notice that
    (new Foo).foo;     // is still 0
    

    So, we did only use properties of that object and are happy with it. But all of them are “public”, and can be overwritten/changed/deleted! If that doesn’t matter you, you’re lucky. You can indicate “privateness” of properties by prefixing their names with underscores, but that’s only a hint to other developers and may not be obeyed (especially in error).

    So, clever minds have found a solution that uses the constructor function as a closure, allowing the creating of private “attributes”. Every execution of a javascript function creates a new variable environment for local variables, which may get garbage collected once the execution has finished. Every function that is declared inside that scope also has access to these variables, and as long as those functions could be called (e.g. by an event listener) the environment must persist. So, by exporting locally defined functions from your constructor you preserve that variable environment with local variables that can only be accessed by these functions.

    Let’s see it in action:

    function Foo() {
        var bar = "foo"; // a local variable
        this.getBar = function getter() {
            return bar; // accesses the local variable
        }; // the assignment to a property makes it available to outside
    }
    
    var foo = new Foo; // an object with one method, inheriting from a [currently] empty prototype
    foo.getBar(); // "foo" - receives us the value of the "bar" variable in the constructor
    

    This getter function, which is defined inside the constructor, is now called a “privileged method” as it has access to the “private” (local) “attributes” (variables). The value of bar will never change. You also could declare a setter function for it, of course, and with that you might add some validation etc.

    Notice that the methods on the prototype object do not have access to the local variables of the constructor, yet they might use the privileged methods. Let’s add one:

    Foo.prototype.getFooBar = function() {
        return this.getBar() + "bar"; // access the "getBar" function on "this" instance
    }
    // the inheritance is dynamic, so we can use it on our existing foo object
    foo.getFooBar(); // "foobar" - concatenated the "bar" value with a custom suffix
    

    So, you can combine both approaches. Notice that the privileged methods need more memory, as you create distinct function objects with different scope chains (yet the same code). If you are going to create incredibly huge amounts of instances, you should define methods only on the prototype.

    It gets even a little more complicated when you are setting up inheritance from one “class” to another – basically you have to make the child prototype object inherit from the parent one, and apply the parent constructor on child instances to create the “private attributes”. Have a look at Correct javascript inheritance, Private variables in inherited prototypes, Define Private field Members and Inheritance in JAVASCRIPT module pattern and How to implement inheritance in JS Revealing prototype pattern?

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

Sidebar

Related Questions

The language is Java. Given this: public static void main(String[] args) { Boolean b1
my language to parse contains statements like public var a, b = 42, c;
Language: PHP / Using Class Upload by Colin Verot About: Multiple Uploading The code
Language: asp This is sample of my code: str = www.example.com/gotobuy.aspx?id=1234 key_word = .obuy.
The language is R. I have a couple of files: utilities.non.foo.R utilities.foo.R utilities.R foo
The language shortcut public string Code { get; set; } saves a bit of
Language: Javascript (PHP page) I have 2 buttons on a page: -- One is
Problem Language: C# 2.0 or later I would like to register context handlers to
Every language that supports Object Orientation has a port of xUnit. What about for
LANGUAGE: I am writing an object-oriented code in MATLAB. I wrote almost all of

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.