Search code examples
javascriptinheritanceobjectfunction-prototypes

Javascript inherit from array and make it global


The small demo below illustrates my problem:

// 1 - Define a global reference to classA
(function() {
    window.classA = new ClassA();
})();

// 2 - ClassA object definition
function ClassA() {
    this.test1 = function() {
        document.write('test1');
    };
}

// 3 - ClassA inherits Array and has a test function
ClassA.prototype = new Array;
ClassA.prototype.test2 = function() {
    document.write(this[0]);
}

// 4 - Test our ClassA
var c = new ClassA();
c.test1();
c.push('test2');
c.test2();

// 5 - Test our global ClassA
classA.test1();
classA.push('test2'); // doesn't work
classA.test2(); // doesn't work

Try it here: http://jsfiddle.net/SPSW4/

What is the proper way to define a global variable classA (ClassA instance)?


Solution

  • Your code appears to be binding the global classA variable before ClassA is fully defined. I believe you will have more luck if you do it like:

    // 1 - define ClassA 
    window.ClassA = function() {
        this.test1 = function() {
            document.write('test1');
        };
    };
    ClassA.prototype = new Array;
    ClassA.prototype.test2 = function() {
        document.write(this[0]);
    }
    
    // 2 - Define a global reference to classA
    window.classA = new ClassA();
    
    // 3 - Test our ClassA
    var c = new ClassA();
    c.test1();
    c.push('test2');
    c.test2();
    
    // 4 - Test our global ClassA
    classA.test1();
    classA.push('test2'); // doesn't work
    classA.test2(); // doesn't work
    

    Here's an example: http://jsfiddle.net/SPSW4/2/