Why I cannot access my variable simply by my_layer.some_var?

For example:

var MyLayer = cc.Layer.extend({
    some_var: "some",
    ctor:function(){
        this._super();
        some_var = "new some";
        //this.some_var = "new some";    //ReferenceError: some_var is not defined
    },
    getSomeVar: function() {
        return some_var;
    },
    getAnotherVar: function() {
        return this.some_var;
    }
});

var my_layer = new MyLayer();
my_layer.some_var;    //"some"
my_layer.getSomeVar();    //"new some"
my_layer.getAnotherVar();    //"some"

I cannot set it by this.some_var in ctor, and obviously this.some_var and some_var are not the same thing…Why?

Hi @miemiekismet

cc.Layer.extend() is declared in the prototype.
You can try it:

my_layer.prototype.some_var; //"some"

It should work correctly, there must be something else wrong

Thank you for your reply.
And I found it in my_layer.proto.some_var;
I can not understand why cocos2d make it so complicate?
Maybe it doesn’t want me to access variable from outside directly?

It really don’t work, you can copy the code and run it in console.
I found some_var, now it is my_layer.proto.some_var.

var MyLayer = cc.Layer.extend({
    some_var: "some",
    ctor:function(){
        this._super();
        some_var = "new some";
        //this.some_var = "new some";    //ReferenceError: some_var is not defined
    },
    getSomeVar: function() {
        return some_var;
    },
    getAnotherVar: function() {
        return this.some_var;
    }
});

var my_layer = new MyLayer();
my_layer.some_var;    //"some"
my_layer.getSomeVar();    //"new some"
my_layer.getAnotherVar();    //"some"

I see the problem here :smile:

In the ctor function, you wrote some_var = "new some";, it should be this.some_var = "new some"

The real secret is the relationship between the prototype and an object

Our extend function extend in fact the prototype, so let me explain several stage in the instantiation process:

  1. initially some_var is stored in the prototype of MyLayer.
  2. Instantiation of MyLayer will create an object of it, at this moment, it didn’t have any internal property, all properties are stored in the prototype.
  3. After the object being created, the engine will invoke ctor function for you, then this.some_var = "new some" will create a property some_var within the object scope and give it the new value. And at this moment, some_var in the prototype scope equals always to “some”

As you wrote some_var instead of this.some_var, it create only a local variable with value equals to new some. So when you query my_layer.some_var, it will query the some_var variable in MyLayer’s prototype, so the value is “some”.

It’s a little bit tricky, hope I have made myself clear. Briefly, it’s all about variable scope and the prototype chain.

Thank you so much for your reply, it is quite clear!