views:

42

answers:

2

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...

+2  A: 

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);
aularon
Interesting. So, if I wanted to return the `hey` instance after running `init`, I can't just `return this`, because `this` would refer to `init`. How would I return the parent `this` of init?
Azmisov
Actually, you can do `return this;` and `this` will be referring to `heyInstance`. but when you did `new hey.init()` in your sample code, that `this` was referring to `hey.init` instance, since then what you instantiated was `hey.init` and not `hey`
aularon
Okay, so I just ran a quick test with your code and `heyInstance.check()` is undefined. I guess it has to be `hey.prototype.check` instead of `hey.check`. But is `hey.prototype` cross browser compatible? Say, IE6 and FF2?
Azmisov
Yes, `hey.prototype` is cross browser, it's a JavaScript core syntax.
aularon
A: 

It works for me...

When I paste

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

into Firebug's console, I end up with an alert from hey.check(); and the second log shows an object where foo == 22.

What's not working on your end?

Alex Mcp
It doesn't work when I run `hey.init(22).check()`.
Azmisov