Search code examples
javascriptobjectinstancesextending

JavaScript: get object instances to contain extended variables


So, say I had the following script:

var hey = {
    foo: 1,
    bar: 2,
    baz: 3,
    init: function(newFoo){
        this.foo = newFoo;
        return this;
    }
}
hey.check = function(){
    alert('yeah, new function');
}

Basically, I can call new hey.init(999) and get a new hey variable with hey.foo set to 999. But when I do that, hey.init(999).check() is no longer defined. Is there a way to mimic the script, but allow new hey's to have the extended variables/functions?

EDIT: changed hey.check() to hey.init(999).check() sorry about that...


Solution

  • What you are doing is not actually getting a new hey instance, but a hey.init instance, which only contains foo property.

    I think this is what are you trying to do:

    var hey =function() {
        this.foo = 1;
        this.bar = 2;
        this.baz = 3;
        this.init = function(newFoo){
            this.foo = newFoo;
        }
    }
    hey.check = function(){
        alert('yeah, new function');
    }
    
    
    //now instantiating our class, and creating an object:
    var heyInstance=new hey();
    heyInstance.init(999);
    alert(heyInstance.foo);