object literal - Javascript sub methods / namespacing with constructor functions -
i cannot thank enough time , help! i've searched 2 days , cannot find exact answer. begin:
i've used object literal notation create objects. however, i've come across situation need create multiple instances of same object. believe i'm attempting create "constructor functions":
i need have ability create multiple "window" objects:
var window1 = new window(); var window2 = new window(); var window3 = new window();
i want ability able organize methods such:
window1.errormessage.show(); window2.errormessage.hide(); window3.errormessage.hide();
instead of like:
window1.showerrormessage(); window2.hideerrormessage(); window3.hideerrormessage();
an example of how build window object in literal notation:
var window = { id: null, init : function(id) { this.id = id; }, errormessage : { show : function(message) { // jquery take id of window, // find errormessage html element within window, // insert "message" , show it. }, hide : function() { // jquery take id of window, // find errormessage html element within window , hide it. } } }
an example of how attempt build window object using constructor functions , prototyping:
function window(id) { this.id = id; this.errormessage = function() {} } window.prototype.errormessage = function() {} window.errormessage.prototype.show = function(message) { // jquery take id of window, // find errormessage html element within window, // insert "message" , show it. } window.errormessage.prototype.hide = function() { // jquery take id of window, // find errormessage html element within window , hide it. }
when attempt execute following code:
var window1 = new window(); window1.errormessage.show('an error message');
(ultimately call using:)
this.errormessage.show('an error message');
i receive following console errors firefox:
- typeerror: window.errormessage undefined
- typeerror: window.errormessage.show not function
thank help. appreciate it.
i still declare methods on function's prototype attempted, you'll have declare show
, hide
methods on new errormessage
type. think best , efficient (because instances of errormessage
share same show
, hide
methods) thing (if understand needs correctly).
function window(id) { this.id = id; this.errormessage = new errormessage(); } function errormessage() { } errormessage.prototype.show = function() {} errormessage.prototype.hide = function() {}
Comments
Post a Comment