Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object literal and static variable

Tags:

javascript

Object literal is considered as a static object.

So, object literal should contain only static variable, but in the following piece of code

var obj = {
    a : "hello",
    foo : function(){
        console.log(this.a);
        console.log(obj.a);
    }
};

I can access a, in a static way obj.a and in a non-static way this.a.

Is a a static variable?

like image 594
JohnJohnGa Avatar asked Feb 24 '26 01:02

JohnJohnGa


1 Answers

I think you are confusing a bunch of different things.

You've created an object named obj that has a field named a. That field can be accessed as obj.a (or obj['a'] if you prefer). If you arrange for some other variable to refer to obj, then it's also available via that variable.

One way to arrange for some other variable to point to obj is to take a field of obj which is defined as a function/closure, and invoke it using "method" syntax, as in obj.foo(). That means that inside the body of foo, for the duration of that invocation, the special variable this will refer to obj. Therefore code within that function can access obj.a via this.a.

None of this has anything to do with static vs dynamic scope, or singletons, or "class" vs "instance" members, or any of that. It's just an object.

like image 199
Mark Reed Avatar answered Feb 25 '26 13:02

Mark Reed