473,763 Members | 7,044 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Singleton desing patter approach without function expressions...

I am designing the library, which will hidden all its functions within
singleton object ... So for clients
they will use it like [functional_pref ix].[function_name] eg.

system.getEleme ntWithId('ruler ');
At library side, i will use constructs like follows (at global scope)
eg.

function System() {

function _getElementWith Id(id) {
/*
GENERIC CODE (using first DOM getElementById( id) and if not
successful
using document.all with some checks...)
*/
}

/*
MORE UTIL FUNCS
*/

this.getElement WithId = _getElementWith Id;
/*
MORE ASSIGMENTS like
this.[util_method] = _[util_method];
*/

}

var system = new System();

System = null; /* since System constructor is desinged to produce
singletons, and it
should not be visible after singleton
instantiation.. . */

My question is simple, can i use construct like:

System = null;

, to redefine constructor System reference to null ? If not, then how i
should do it ?
Also remember that i can't use function expressions like

function(...) { }

I will appreciate somebody knowlegable to lighten my problem...

Best regards
Luke Matuszewski

Feb 5 '06 #1
56 3998
Luke Matuszewski wrote:
I am designing the library, which will hidden all its functions within
singleton object ... So for clients
they will use it like [functional_pref ix].[function_name] eg.
There is a better way to do what you're trying to do.
For example, this is simple:

var System = new Object();
System.getEleme ntWithId = function() { }
System.otherFun ction = function() { }
var system = new System();
System = null; /* since System constructor is desinged to produce
singletons, and it
should not be visible after singleton
instantiation.. . */


I don't believe that is a good example of the singleton pattern. Rather than
allowing multiple calls to a getInstance(), all of which return the same
instance, you're just destroying the constructor entirely. Why even bother?

Try this, for example:

var Singleton = (function() {
// This isn't "lazy" instantiation, but you could do that if you wanted
var instance = new Object();
instance.proper ty = Math.random(100 0);
return {'getInstance': function() { return instance; }}
})();

// The next line will generate a script error.
// You should not be able to directly instantiate an instance of the class
var object = new Singleton();

// The proper way to get the class instance
var x = Singleton.getIn stance();
alert(x.propert y); // Alerts random number
var y = Singleton.getIn stance();
alert(y.propert y); // Alerts same random number
alert(x==y); // True - same object

--
Matt Kruse
http://www.JavascriptToolbox.com
http://www.AjaxToolbox.com
Feb 5 '06 #2
Luke Matuszewski wrote:
Also remember that i can't use function expressions like
function(...) { }


Oh, and what does that even mean?

--
Matt Kruse
http://www.JavascriptToolbox.com
http://www.AjaxToolbox.com
Feb 5 '06 #3

Matt Kruse wrote:
Luke Matuszewski wrote:
Also remember that i can't use function expressions like
function(...) { }


Oh, and what does that even mean?


Function expressions is expressions that returns function reference
(EcmaScript 3rd ed.- 13) like:

....
System.someFunc = function() {
/* CODE */
}
....

Function expressions where not present in EcmaScript 2nd and 1st
ed.(only function declarations where present). If i will not use
function expressions, then i could write code that
will run in all browsers (maybe without result, but also without errors
in old browsers if they encounter function expressions).
Also it seems that function expressions, in the form of

var System.someFunc = function identifier(...) { /* syntax allowed
since JavaScript 1.2 and JScript 1.0 */
}

, or in the form of

var System.someFunc = function(...) { /* syntax allowed since
JavaScript 1.5(!) and JScript ?(do not remeber) */
}

My only apprehension is question: can i null'yfi the function
identifier like:

function System() {
/* code */
}

var system = new System();
System = null; /* THIS */

, so System() constructor will not be visible after THIS statement.
(also see that if i can, there is only one object system, so no memory
leaks will happen in IE revelant to many execution contexts...).

Anyway, thanks for such knowlegable examples ;-)
Best regards
Luke Matuszewski

Feb 5 '06 #4

Matt Kruse wrote:
http://www.JavascriptToolbox.com


PS your example in http://www.JavascriptToolbox.com of moving <iframe>
is not strictly valid agains used doctype. Your are using:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">

, and <iframe> is only allowed in loose dtd (see
http://www.w3.org/TR/html4/index/elements.html). To correct it, you
will have to use <object> instead of <iframe>... Thats all according to
specs, but according to real world the <iframe> tag is supported wider
by existing (existed) user agenst than the <object> tag (so maybe to
support all user agents there should be user-agent version checking...
but thats always bad idea).
See
<URL:http://www.cs.tut.fi/~jkorpela/html/iframe.html>
<URL:http://www.w3.org/TR/REC-html40/struct/objects.html#h-13.5>
<URL:http://www.w3.org/TR/2000/NOTE-WCAG10-HTML-TECHS-20000920/#alt-frames>
<URL:http://www.stack.nl/htmlhelp/faq/html/design.html#inc lude-file>
<URL:http://www.webmasterwo rld.com/forum21/6539.htm>
<URL:http://www.webmasterwo rld.com/forum21/11590.htm>

To make a solution, on the page where you present moving <iframe>'s,
use:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">

, as the table on <URL:http://hsivonen.iki.fi/doctype/> suggests (only
Konqueror 3.2 switches to quirk :( ). Also can also use strict doctype
inside iframe's, to maintain standards mode.

Feb 5 '06 #5
VK

Luke Matuszewski wrote:
var system = new System();
System = null; /* THIS */


IE (specially IE 5.x) chokes sometimes on nullifying function
references this way. Nothing to do with ECMA - just IE behavior. It is
more secure (and user friendly) to emulate the GetObject behavior thus
if an instance doesn't exists then create one; if an instance already
exists then return a reference to the existing instance.

function System() {
if (typeof System.instance == 'undefined') {
this.foo = ...
this.bar = ...
System.instance = this;
System.toString = function() {return 'function';}
}
else {
return System.instance ;
}
}

// create instance:
var system = new System();

// this simply returns a reference to
// the existing instance:
var system2 = new System();

I also like to kill toString method for constructor (see above) to
prevent source code dump at runtime. Now alert(System) simply displays
"function". Not obligatory, but may be helpful.

Overall you have to remember that it is nothing like in say C++. In
compiled languages all these public/private/singleton/multiton :-)
indeed produce compiled binary code with some predefined behavior, and
to change that behavior one has either to crack the code or to steal
the source. In JavaScript anyone can open your .js file and make all
your private members public or transform your singleton into an
auto-multiplying object.
So your concern should be about *runtime* only in two aspects only:
1) occasional environment damage (say some vital property overriden by
mistake due say a name conflict)
2) script highjaking (so your script is forced to act in a
non-desirable way or expose non-desirable property) - once again *at
runtime*

Feb 5 '06 #6
VK

Luke Matuszewski wrote:
PS your example in http://www.JavascriptToolbox.com of moving <iframe>
is not strictly valid agains used doctype. Your are using:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
Which is always a bad idea because strict.dtd is defective and never
was corrected since the original publication in 1999

It doesn't have <iframe> which alone makes it unusable in the modern
Web. Also it has some rude mistakes in form element definitions (like
missing "wrap" attribute for textarea).

Also it worth to point out that is someone is really crazy about
standard perfectness then HTML 4.01 should be connected with the
relevant DTD:
<http://www.w3.org/TR/html401/strict.dtd>

because <http://www.w3.org/TR/html4/strict.dtd> points to the previous
version (HTML 4.0)

It has no practical sense though because both
<http://www.w3.org/TR/html4/strict.dtd> and
<http://www.w3.org/TR/html401/strict.dtd> are exact copies of the very
same document (?!?!?)

Whoever is wondering what a hey they can try to reach someone Dave
Raggett <ds*@w3.org> who's claimed to be the author of both
masterpieces.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">


Again the really correct version is:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html401/loose.dtd">

(with the same practical outcome - namely with a total absence of such)

Feb 5 '06 #7
Luke Matuszewski wrote:
Function expressions where not present in EcmaScript 2nd and 1st
ed.(only function declarations where present). If i will not use
function expressions, then i could write code that
will run in all browsers


If you can name a browser that is still in use that does not support
function expressions, you might have a point.
Writing code that still supports Netscape 2.0, for example, is a pointless
exercise.

--
Matt Kruse
http://www.JavascriptToolbox.com
http://www.AjaxToolbox.com
Feb 5 '06 #8

VK napisal(a):
Luke Matuszewski wrote:
PS your example in http://www.JavascriptToolbox.com of moving <iframe>
is not strictly valid agains used doctype. Your are using:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
Which is always a bad idea because strict.dtd is defective and never
was corrected since the original publication in 1999


I must not agreed. For me standard that was accepted and largely
disscused at HTML ERB before formalization is good standard (also HTML
4.0 what certified in 1998 and HTML 4.01 is bugfixed version of that
HTML 4.0 standard defined in december of 1999).

It doesn't have <iframe> which alone makes it unusable in the modern
Web. You can always use XmlHttpObject (AJAX) to make <iframe> emulation
inside <div> (using responseText as innerHtml or even as
document.write( XmlHttpObjectIn stance.response Text).
Also it worth to point out that is someone is really crazy about
standard perfectness then HTML 4.01 should be connected with the
relevant DTD:
<http://www.w3.org/TR/html401/strict.dtd>

because <http://www.w3.org/TR/html4/strict.dtd> points to the previous
version (HTML 4.0)

It has no practical sense though because both
<http://www.w3.org/TR/html4/strict.dtd> and
<http://www.w3.org/TR/html401/strict.dtd> are exact copies of the very
same document (?!?!?)
Again i will not agree.
To answer why i suggested :

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">

, i will point you to <URL:http://hsivonen.iki.fi/doctype/> (and if you
don't like to read much i will explain that with above doctype user
agents presented on table will "switch" themself to standards mode
(which means that they will try to use standards defined by w3c.org
concerning CSS and HTML when they will render the web page)... so for
me i will use:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">

or even:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd"> <!--Which allow me to use
<iframe> techniques-->

I know that you like IE (or are interested in IE), and so even on
microsoft site you can see my examples of doctype. See
<URL:http://msdn.microsoft. com/library/default.asp?url =/library/en-us/dnie60/html/cssenhancements .asp>

Whoever is wondering what a hey they can try to reach someone Dave
Raggett <ds*@w3.org> who's claimed to be the author of both
masterpieces.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">


Again the really correct version is:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html401/loose.dtd">


No. As you can see, even HTML 4.01 Recomendation specifies

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">

or

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">

See <URL:http://www.w3.org/TR/html401/struct/global.html#h-7.2> (which
is your HTML 4.01 Specification).

So first look inside specs before you will use words like 'no practical
sense' or 'defective'. I your words are true then organizations like:
MIT <URL:http://www.lcs.mit.edu/>,
INRIA <URL:http://www.inria.fr/>
Keio <URL:http://www.keio.ac.jp/>
and at last but not least W3C <URL:http://www.w3.org/>
, will have to be also with 'no practical sense' or 'defective'.

Best regards.
Luke M.

Feb 5 '06 #9

Matt Kruse napisal(a):
Luke Matuszewski wrote:
Function expressions where not present in EcmaScript 2nd and 1st
ed.(only function declarations where present). If i will not use
function expressions, then i could write code that
will run in all browsers


If you can name a browser that is still in use that does not support
function expressions, you might have a point.
Writing code that still supports Netscape 2.0, for example, is a pointless
exercise.


Agree. From my point of view, scripts that work down to Netscape 4.0x
(in a sense that they do not do harm, including memory leaks provided
by circular references between ActiveX objects and DOM objects in IE)
are well written. From this point (Netscape 4.0x) you can always use
function expression syntax below:

System.myFunc = function
identifierOnlyF orReferencingIn sideThisFunctio n() {

}

(the syntax: function(...) { } is only supported from JavaScript
1.5(Netscape 6.x), thus should be avoided if writting scripts that
should run on them too).

Again ***thanks*** for knowlegable examples from Matt Kruse and VK.

Best regards.
Luke M.

PS Matt you can update your http://www.AjaxToolbox.com to suppor
IceBrowser see <URL:http://www.jibbering.c om/2002/4/httprequest.htm l>
(window.createR equest)

Feb 5 '06 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

10
8295
by: JohnS | last post by:
Hi, A lot of functions (classes) in my JavaScript app are singletons. So, I have been exploring ways making JavaScript functions singletons. I thought I'ld run one idea past you all and get some feed back. The usual method of making singletons is to have a static member that returns one instance of the class. But, JavaScript has no notion of static. The closest it has is prototype functions.
1
2037
by: Richard A. DeVenezia | last post by:
foo() generates elements with event handlers that invoke foo function properties. Is this an abhorrent or misthought pattern ? It allows just the one occurence of identifier /foo/ to be changed to /whatever/ when need arises and everything should still work. function foo () { var callee = arguments.callee
4
8241
by: Eric | last post by:
Perhaps this question has been posed before (I'd be surprised if it hasn't) but I just gotta know... Is it possible to combine the Singleton and Factory Method design patterns in the same class? Let's start with your basic Singleton class: class Singleton {
10
1508
by: JFR | last post by:
i found this code sample on the net that i wanted to use: class CUniqueObject { private: CUniqueObject( void ) : m_iValue(0) { } ~CUniqueObject( void ) { }
2
1688
by: davidw | last post by:
As I asked in last post, I want to put some logic in a object and all my webcontrol instance will access that object, the object is responsed to retrieve data from database if the data has not been retrieved yet. Vadym Stetsyak suggested me to use singleton, it seems a good solution for me, but after I read more about singleton, I find another issue - if I use singleton patter, I can not store context data in the class anymore. How I used...
21
2467
by: Sharon | last post by:
I wish to build a framework for our developers that will include a singleton pattern. But it can not be a base class because it has a private constructor and therefore can be inherit. I thought maybe a Template can be use for that, but C# does not support Templates (will be C# generics in mid 2005). Does anyone have a solution on how the singleton pattern can be written, in C#, as a framework/ infrastructure class, so users can use this...
10
3327
by: wkaras | last post by:
Why aren't "Singletons" done like this in C++: A.hpp: class A { public: static A theA; // ...
3
2815
by: koredump | last post by:
I have inherited a Business Object architecture that makes heavy use of the Singleton design patter. For example the data access layer class is implemented as a static Singleton "object", there are also other business objects logic and security supporting classes that are all implemented using the Singleton patter. I 'm attempting to make use of this class library in a webservice application. The problem is that some of the Singleton...
1
1500
by: =?Utf-8?B?Qi4gQ2hlcm5pY2s=?= | last post by:
I'm getting a little confused here. I have a C# class that I'm trying to translate to VB. The C# class is essentially: public static class Class1 { ..... some private static variables and public static properties. } The translation (from several different translation programs) is:
0
9386
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10144
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9997
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9822
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7366
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5270
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5405
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
3522
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2793
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.