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...
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);
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?
精彩评论