tags:

views:

66

answers:

1

John Resig’s Simple Javascript Inheritance: http://ejohn.org/blog/simple-javascript-inheritance/

I tried to do such thing:

var SomeClass = Class.extend({
    init: function() {
        var someFunction = function() {
            alert(this.someVariable);
        };

        someFunction(); // should alert "someString"
    },

    someVariable: "SomeString"
});

var someClass = new SomeClass();

This should alert "someString", but it doesn't because inside the closure function someFunction, the value of this doesn't refers to the class, it is changed. That makes me unable to get access to the properties and functions of the class inside a closure function.

Any suggestions?

+4  A: 

I believe your problem lies in what "this" refers to. "this" is referring to the function in this case, not the object. What you want is probably:

var SomeClass = Class.extend({
    init: function() {
        var self = this;
        var someFunction = function() {
            alert(self.someVariable);
        };

        someFunction(); // should alert "someString"
    },

    someVariable: "SomeString"
});

var someClass = new SomeClass();
Jamie Wong
That's what I actually use, but I came here because I search for other method. Using this method makes me write **var self = this;** like 20 times in a page :\
Zippo
You could do something like this: http://www.sitecrafting.com/blog/underscore-trick
Jamie Wong
I'll try that, thank you =]
Zippo