How to call key of object inside of object without "this"

Go To StackoverFlow.com

0

I started using Base.js for a class inheritance. In Base.js a class should be an object, but does not function.

This creates a problem:

    ​var obj = {
    variable:true,
        func:function(){
            console.log(variable);
        }
    };

    obj.func();​

This code throw error: "Uncaught ReferenceError: variable is not defined". This is because "console.log(variable);" does not have "this".

But i dont want write "this" in ALL functions in my large class.

Is there any way around this?

2012-04-04 07:11
by Boyo
Writing this.whatever instead of whatever is exactly what you are supposed to do in JavaScript. Same applies e.g. in Python and LUA. It's actually a good thing since you immediately see if you access a member variable or a local/global. Please do not look for ways to pervert a language just because you "don't want to" do something everyone else does in that language, too - ThiefMaster 2012-04-04 07:20


0

You can always write one line of extra code: var ins_obj = this; but you would still have to put ins_obj.variable in the console.log. Any language i have used does these things like this. this.variable is the way to call variables, functions inside an object.

2012-04-04 07:18
by Stijn_d
"Any language i have used does these things like this. this.variable is the way to call variables, functions inside an object." Yes and this ok. But i use object as class. And write "this" all times very tediously - Boyo 2012-04-04 08:51
Ads