473,796 Members | 2,737 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Cancelling instantiation

Other than throwing an exception during the execution of an object's
constructor, is there any way to cancel creation of the object in such a
way that it leaves a reference to it null or undefined. That would enable
the simple test:

var ref = new someObject();

if( ref ) {
// Object created successfully
}

I know one could use state flags instead, but the object I have in mind
shouldn't exist if the arguments passed to it are incorrect (there is a
good reason, trust me).

[OT - Exceptions in general (including other languages)]

Some people seem to have issues concerning throwing an exception during
object construction to signify failure and instead prefer to use state
flags. Any thoughts either way?

[/OT]

By the way, it's not possible to have protected[1] members in JavaScript,
is it? Shame...

Many thanks,
Mike
[1] I do mean protected, not private.

--
Michael Winter
M.******@blueyo nder.co.invalid (replace ".invalid" with ".uk" to reply)
Jul 20 '05 #1
16 1367
Michael Winter wrote:
Other than throwing an exception during the execution of an object's
constructor, is there any way to cancel creation of the object in
such a way that it leaves a reference to it null or undefined.
No, the only circumstances where a call to the internal [[Construct]]
method of a constructor will not result in the return of the created -
this - object is when the internal call to the [[Call]] method returns a
value of Type object (as opposed to typeof "object").
That would enable the simple test:
Maybe you could return an object that can be (probably indirectly)
converted to boolean false in a way that could not normally be achieved
with the constructed object. EG:-

function Const(arg1){
if(!arg1){
return (new String(""));
}
}

var a = new Const(false);

if(String(a)){
alert('Object constructed');
}else{
alert('Empty string object returned');
}

- but it would be important that the object not overload the
Object.prototyp e.toString method in such a way as to (ever) return an
empty string. Or:-

function Const(arg1){
if(!arg1){
return (new Number(0));
}
}

var a = new Const(false);

if(Number(a)){
alert('Object constructed');
}else{
alert('Empty string object returned');
}

<snip> [OT - Exceptions in general (including other languages)]

Some people seem to have issues concerning throwing an exception
during object construction to signify failure and instead prefer
to use state flags. Any thoughts either way?
For cross-browser client-side scripting try-catch cannot yet be used
because the older of the browsers currently in use regard them as
reserved words, generate syntax errors as the code loads and never even
attempts to execute it. (Which is one of the reasons that so much effort
gets put into testing the environment, so exceptions are not thrown and
there is no need to handle them.)
By the way, it's not possible to have protected[1] members in
JavaScript, is it? Shame... <snip> [1] I do mean protected, not private.


They can be emulated but the effort, introduced overheads and code bloat
would probably negate any advantage.

Richard.
Jul 20 '05 #2
Richard Cornford wrote: <c2************ *******@news.de mon.co.uk>
<snip>
... . Or:-

function Const(arg1){
if(!arg1){
return (new Number(0));
}
}

var a = new Const(false);

if(Number(a)){
alert('Object constructed');
}else{
alert('Empty string object returned');
}

<snip>

That version will not work as the object would be converted to NaN,
which would than convert to boolean false. Unless maybe the object
deliberately overloaded the valueOf method, or the returned Number
object was non zero and the logic of the test reversed. Probably better
just to use the String version.

Richard.
Jul 20 '05 #3
<snip>
By the way, it's not possible to have protected[1] members in
JavaScript, is it? Shame...


No, this is one of the great fallacies about Javascript. Javascript
supports closures and therefore supports protected/private members. See:

http://www.crockford.com/javascript/private.html
Jul 20 '05 #4
On Mon, 1 Mar 2004 21:28:56 -0000, Richard Cornford
<Ri*****@litote s.demon.co.uk> wrote:
Michael Winter wrote:
Other than throwing an exception during the execution of an object's
constructor, is there any way to cancel creation of the object in
such a way that it leaves a reference to it null or undefined.


No, the only circumstances where a call to the internal [[Construct]]
method of a constructor will not result in the return of the created -
this - object is when the internal call to the [[Call]] method returns a
value of Type object (as opposed to typeof "object").


I can work with that...
That would enable the simple test:


Maybe you could return an object that can be (probably indirectly)
converted to boolean false in a way that could not normally be achieved
with the constructed object. EG:-

function Const(arg1){
if(!arg1){
return (new String(""));
}
}

var a = new Const(false);

if(String(a)){
alert('Object constructed');
}else{
alert('Empty string object returned');
}

- but it would be important that the object not overload the
Object.prototyp e.toString method in such a way as to (ever) return an
empty string.


[snipped number-based, problematic approach]

After reading the above, and the latest JavaScript reference (by Netscape)
concerning exceptions, I took a slightly different approach:

function Exception( msg ) {
this.message = msg;
}

function Obj( err ) {
if( err ) return new Exception( 'Some text' );

// Continue with object construction...
}

var a = new Obj( true );

if( a instanceof Exception ) {
// Error during construction...

Once exceptions in JavaScript have matured, this could be changed to:

function Obj( err ) {
if( err ) throw new Exception( 'Some text' );

// Continue with object construction...
}

try {
var a = new Obj( true );
} catch( e ) {
// Error during construction...
}

It appears to be an acceptable solution, and would provide a trivial
conversion to exceptions further down the road.
Some people seem to have issues concerning throwing an exception
during object construction to signify failure and instead prefer
to use state flags. Any thoughts either way?


For cross-browser client-side scripting try-catch cannot yet be used
because the older of the browsers currently in use regard them as
reserved words, generate syntax errors as the code loads and never even
attempts to execute it. (Which is one of the reasons that so much effort
gets put into testing the environment, so exceptions are not thrown and
there is no need to handle them.)


You don't happen to know when exceptions were introduced, do you? I was
quite surprised to find that IE 5 is supposed to support exceptions. I'm
sure someone doubted that even IE 6 supported them.
By the way, it's not possible to have protected[1] members in
JavaScript, is it? Shame...

<snip>
[1] I do mean protected, not private.


They can be emulated but the effort, introduced overheads and code bloat
would probably negate any advantage.


That's what I thought. Just checking that I wasn't missing anything.

Thanks Richard,
Mike

--
Michael Winter
M.******@blueyo nder.co.invalid (replace ".invalid" with ".uk" to reply)
Jul 20 '05 #5
On Tue, 02 Mar 2004 13:55:07 GMT, Michael Winter
<M.******@bluey onder.co.invali d> wrote:

[snip]
try {
var a = new Obj( true );
} catch( e ) {
// Error during construction...
}


That should be more like:

var a = null;

try {
a = new Obj( true );
} catch( e ) {
// Error during construction...
}

Mike

--
Michael Winter
M.******@blueyo nder.co.invalid (replace ".invalid" with ".uk" to reply)
Jul 20 '05 #6
Michael Winter wrote:
Richard Cornford wrote: <snip> After reading the above, and the latest JavaScript reference (by
Netscape) concerning exceptions, I took a slightly different approach:

function Exception( msg ) {
I would be concerned whether "Exception" was already defined in any
execution environment. It doesn't seem that unlikely a name to be in
use, maybe "ObjectConstruc tionException" or something shorter.

<snip> if( a instanceof Exception ) {
I think - instanceof - may have entered the language at about the same
point as try-catch. (I have got a copy of the 3nd edition of ECMA 262
which I could e-mail you if you are interested)

<snip> You don't happen to know when exceptions were introduced, do you? I
was quite surprised to find that IE 5 is supposed to support
exceptions. I'm sure someone doubted that even IE 6 supported them.


ECMAScript 3rd edition, JavaScript 1.4 and JScript 5.

<snip>
They can be emulated but the effort, introduced overheads and code
bloat would probably negate any advantage.


That's what I thought. Just checking that I wasn't missing anything.


For completeness here is how it could be done:-

The Emulation of Protected Members with Javascript.

The concept of package does not exist in javascript so it is not
practical to define protected in terms of accessibility only to members
of the same package and subclass as in Java. Instead protected is going
to be considered in terms of restricting the accessibility of members to
objects that belong to the same "Class" (built with the same
constructor) or objects that belong to a group of pre-defined related
"Classes". The potential for the use of protected members in subclasses
exists, to the extent that this type of javascript object can be
subclassed.

While it is possible for private instance members (including method) to
be successfully emulated with javascript, for interaction between object
the getters and setters for any protected functionality will themselves
have to be public. Data members will be implemented as private members
with getters and setters to control their accessibility to other
classes. The emulation cannot be done in terms of the visibility of the
getters and setters, instead their willingness to act will be restricted
to interactions initiated by a limited set of classes.

To restrict interactions to a within limited set of classes those
classes are going to need a way of identifying each other as belonging
to that set. This can be done with a shared secret, but it is going to
have to be a secret that cannot be accessed outside of the set of
classes. Similarly there will need to be a mechanism to pass that secret
between classes in the set without exposing the secret and in a way that
cannot be hijacked by external code.

In the same way as closures provide a method of emulating private static
and instance members that are not accessible outside of the Class or
instance in question, they can be used to hold information that is only
available to a group of classes:

(function(){
/* Assign a reference to the global object (this in a function
expression executed inline) to the local variable - global
- so that properties of the global object can be created
relative to it:
*/
var global = this;
/* Create an object to act as the shared secret for the two (or
possibly more) constructors defined during the execution of
this inline function expression. Later, when the complexity
of this closer increases to include (private) method at this
level, one of those methods may be used instead of this
object:
*/
var secret = {};
/* Execute another function expression inline such that it returns
a function object that can act as the constructor for objects
and assign that constructor to a global property called
"ClassA":
*/
global.ClassA = (function(){
/* This inner function definition will act as the constructor
for "ClassA":
*/
function constr(){
/* We do not want our constructor being called as a
function:
*/
if(this == global)return;
/* Ensure that each object instance created with this
constructor holds a reference to its object instance
(will be employed later to ensure that protected
methods can only be executed as methods of this object):
*/
var self = this;
}
/* return a reference to the inner function defined above:
*/
return constr;
})();
/* Execute another function expression inline such that it returns
a function object that can act as the constructor for objects
and assign that constructor to a global property called
"ClassB":
*/
global.ClassB = (function(){
/* This inner function definition will act as the constructor
for "ClassA":
*/
function constr(){
/* We do not want our constructor being called as a
function:
*/
if(this == global)return;
/* Ensure that each object instance created with this
constructor holds a reference to its object instance
(will be employed later to ensure that protected
methods can only be executed as methods of this object):
*/
var self = this;
}
/* return a reference to the inner function defined above:
*/
return constr;
})();
})();

That is the basic framework. It doesn't have any emulation of protected
members yet but the variable - secret - is only available from code
defined within the outer function expression. That code includes that
two class constructors so all instances created with those constructors
has access to the - secret - variable and can use the unique identity of
that object to verify that instructions to access any members it is
regarding as protected are only modified by code that shares that
secret. Code external to the outer function expression cannot access
the - secret - object.

Now to add the mechanics for getting and setting the protected members
and executing (publicly exposed but protected in execution) methods. My
thirst thought in this direction had the - secret - object passed by
reference with the various method calls but it occurred to me that that
would allow the objects to be tricked into giving up their secret. The
secret must stay within its closure, as must any protected data, so
instead I am going to use a series of variables within the same level of
the closure as - secret - to provide a transfer location for the values
and a semaphore mechanism for the requests:

(function(){
var global = this;
var secret = {};
var requestToRead = null;
var requestToSet = null;
var requestToExecut e = null;
var validTransfer = null;
var transferValue;
global.ClassA = (function(){
function constr(){
if(this == global)return;
var self = this;
var protectedMember OfA = 5;
this.getProtect edMemberOfA = function(){
/* First ensure that the function is being executed as
a method of this object:
*/
if(this == self){
/* Check to see that the - requestToGet - variable
has been set to the correct secret:
*/
if(requestToGet == secret){
/* All is well so expose the -
protectedMember OfA - value to the calling
object (indirectly via the private -
transferValue - variable):
*/
transferValue = protectedMember OfA;
validTransfer = secret;
}
}
/* Null the - requestToGet - variable:
*/
requestToGet = null;
}
this.setProtect edMemberOfA = function(){
/* First ensure that the function is being executed as
a method of this object:
*/
if(this == self){
/* Check to see that the - requestToSet - variable
has been set to the correct secret:
*/
if(requestToSet == secret){
/* All is well so set the - protectedMember OfA
- (indirectly from the private -
transferValue - variable):
*/
protectedMember OfA = transferValue;
}
}
/* Null the - requestToSet - variable:
*/
requestToSet = null;
}
this.incrementP rotectedMemberO fA = function(){
/* First ensure that the function is being executed as
a method of this object:
*/
if(this == self){
/* Check to see that the - requestToExecut e -
variable has been set to the correct secret:
*/
if(requestToExe cute == secret){
/* All is well, so act: */
protectedMember OfA++;
}
}
/* Null the - requestToExecut e - variable:
*/
requestToExecut e = null;
}
this.passOnProt MemOfAToClassBI nst = function(classB inst){
/* First ensure that the function is being executed as
a method of this object and that the object passed
by reference has the required method:
*/
if((this == self)&&(classBi nst.setProtecte dMemberOfB)){
/* Set up the interaction with the instance of
ClassB by assigning - secret - to the -
requestToSet - variable:
*/
requestToSet = secret;
/* The place the value of - protectedMember OfA - in
a location that is accessible to instances of
the appropriate classes:
*/
transferValue = protectedMember OfA;
/* Call the protected setter on the instance of
ClassB:
*/
classBinst.setP rotectedMemberO fB();
/* Null the - requestToSet - variable:
*/
requestToSet = null;
}
}
this.setProtMem OfAToClassBInst ProM = function(classB inst){
/* First ensure that the function is being executed as
a method of this object and that the object passed
by reference has the required method:
*/
if((this == self)&&(classBi nst.getProtecte dMemberOfB)){
/* Set up the interaction with the instance of
ClassB by assigning - secret - to the -
requestToGet - variable:
*/
requestToGet = secret;
/* Call the protected getter on the instance of
ClassB:
*/
classBinst.getP rotectedMemberO fB();
/* If the call was to a valid getter the -
requestToGet - variable should have been nulled,
and successful data transfer will be marked by
the - validTransfer - variable knowing the
secret:
*/
if((!requestToG et)&&(validTran sfer == secret;)){
/* Assign the value of the - transferValue -
variable to the local protected member:
*/
protectedMember OfA = transferValue;
}
/* Null the - requestToGet - variable: */
requestToGet = null;
/* Null the - validTransfer - variable: */
validTransfer = null;
}
}
}
return constr;
})();
global.ClassB = (function(){
function constr(){
if(this == global)return;
var self = this;
var protectedMember OfB = 8;
this.getProtect edMemberOfB = function(){
/* First ensure that the function is being executed as
a method of this object:
*/
if(this == self){
/* Check to see that the - requestToGet - variable
has been set to the correct secret:
*/
if(requestToGet == secret){
/* All is well so expose the -
protectedMember OfB - value to the calling
object (indirectly via the private -
transferValue - variable):
*/
transferValue = protectedMember OfB;
validTransfer = secret;
}
}
/* Null the - requestToGet - variable:
*/
requestToGet = null;
}
this.setProtect edMemberOfB = function(){
/* First ensure that the function is being executed as
a method of this object:
*/
if(this == self){
/* Check to see that the - requestToSet - variable
has been set to the correct secret:
*/
if(requestToSet == secret){
/* All is well so set the - protectedMember OfB
- (indirectly from the private -
transferValue - variable):
*/
protectedMember OfB = transferValue;
}
}
/* Null the - requestToSet - variable:
*/
requestToSet = null;
}
this.incrementP rotectedMemberO fB = function(){
/* First ensure that the function is being executed as
a method of this object:
*/
if(this == self){
/* Check to see that the - requestToExecut e -
variable has been set to the correct secret:
*/
if(requestToExe cute == secret){
/* All is well, so act: */
protectedMember OfB++;
}
}
/* Null the - requestToExecut e - variable:
*/
requestToExecut e = null;
}
this.passOnProt MemOfBToClassAI nst = function(classA inst){
/* First ensure that the function is being executed as
a method of this object and that the object passed
by reference has the required method:
*/
if((this == self)&&(classBi nst.setProtecte dMemberOfA)){
/* Set up the interaction with the instance of
ClassA by assigning - secret - to the -
requestToSet - variable:
*/
requestToSet = secret;
/* The place the value of - protectedMember OfB - in
a location that is accessible to instances of
the appropriate classes:
*/
transferValue = protectedMember OfB;
/* Call the protected setter on the instance of
ClassA:
*/
classAinst.setP rotectedMemberO fA();
/* Null the - requestToSet - variable:
*/
requestToSet = null;
}
}
this.setProtMem OfBToClassAInst ProM = function(classA inst){
/* First ensure that the function is being executed as
a method of this object and that the object passed
by reference has the required method:
*/
if((this == self)&&(classBi nst.getProtecte dMemberOfA)){
/* Set up the interaction with the instance of
ClassA by assigning - secret - to the -
requestToGet - variable:
*/
requestToGet = secret;
/* Call the protected getter on the instance of
ClassA:
*/
classAinst.getP rotectedMemberO fA();
/* If the call was to a valid getter the -
requestToGet - variable should have been nulled,
and successful data transfer will be marked by
the - validTransfer - variable knowing the
secret:
*/
if((!requestToG et)&&(validTran sfer == secret;)){
/* Assign the value of the - transferValue -
variable to the local protected member:
*/
protectedMember OfB = transferValue;
}
/* Null the - requestToGet - variable: */
requestToGet = null;
/* Null the - validTransfer - variable: */
validTransfer = null;
}
}
}
return constr;
})();
})();

Thus only objects constructed as instances of ClassA and ClassB are able
to interact in certain ways, emulating a concept of "protected" . As you
can see the effort to implement is considerable and probably not worth
the gains (if any). I can live without this particular aspect of OO,
after all we will not be implementing aircraft fly-by-wire systems in
javascript, or anything so complex that the simpler emulations of
private instance and static members won't provide all the data hiding
that is needed.

Richard.
Jul 20 '05 #7
Richard Cornford wrote:
<snip>
... (I have got a copy of the 3nd edition of ECMA 262 ^
That should have been 2nd edition.
which I could e-mail you if you are interested)

<snip>

Richard.
Jul 20 '05 #8
"Richard Cornford" <Ri*****@litote s.demon.co.uk> writes:
Richard Cornford wrote:
<snip>
... (I have got a copy of the 3nd edition of ECMA 262

^
That should have been 2nd edition.


I was about to say "me too", but found that it can be downloaded
at <URL:http://www.mozilla.org/js/language/> (along with version 1).

/L
--
Lasse Reichstein Nielsen - lr*@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleD OM.html>
'Faith without judgement merely degrades the spirit divine.'
Jul 20 '05 #9
Richard Cornford wrote:

<--snip-->

(I have got a copy of the 3nd edition of ECMA 262
which I could e-mail you if you are interested)


I am please.

--
Randy
Chance Favors The Prepared Mind
comp.lang.javas cript FAQ - http://jibbering.com/faq/
Jul 20 '05 #10

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

Similar topics

1
1886
by: Paul THompson | last post by:
I have been working for some time to 1) detect tab and shift tab events 2) control the focus on the basis of these events. I have found that I can do this, but continue to have nagging problems. One of the main problems at this point lies in cancelling the event. I have found that the TAB fires the onkeypress in NN, but not in IE. I can cancel the onkeypress fine in NN. The TAB fires the onkeydown in IE and can be cancelled in IE. ...
7
1696
by: johny smith | last post by:
Based on my experience there is two ways to instantiate an object. Method 1: Car* car1 = new Car();
7
1710
by: Hunter Hou | last post by:
Hello, I'm trying one example of <<the C++ programming language>> Page 865 int f( int ); template< class T > T g( T t ) { return f( t ); } char c = g( 'a' ); ************ char f( char ); Stroustrup said **** line is wrong because alternative resolution of f( t )
12
2627
by: mlimber | last post by:
This is a repost (with slight modifications) from comp.lang.c++.moderated in an effort to get some response. I am using Loki's Factory as presented in _Modern C++ Design_ for message passing in an embedded environment with multiple processors. I created a policy for classes, which, I had hoped, would automatically register the class with the appropriate factory: // In some header file... #include <cassert>
4
1993
by: Steve Long | last post by:
Hello, I hope this is the right group to post this to. I'm trying to serialize a class I've written and I'd like to be able to serialze to both binary and xml formats. Binary serialization is working fine but when I try to instantiate an XmlSerializer object with: Dim xmls As New XmlSerializer(GetType(CLayerDefinition)) I get the following error:
13
1710
by: Jake Barnes | last post by:
I saw this sentence: "The last stage of variable instantiation is to create named properties of the Variable object that correspond with all the local variables declared within the function." here: http://jibbering.com/faq/faq_notes/closures.html
3
4008
by: Steven T. Hatton | last post by:
Has anybody here used explicit instantiation of templates? Has it worked well? Are there any issues to be aware of? -- NOUN:1. Money or property bequeathed to another by will. 2. Something handed down from an ancestor or a predecessor or from the past: a legacy of religious freedom. ETYMOLOGY: MidE legacie, office of a deputy, from OF, from ML legatia, from L legare, to depute, bequeath. www.bartleby.com/61/
2
1881
by: WittyGuy | last post by:
Hi My class looks something like this: class Base { public: Base () {} ~Base () {} // No virtual dtor in the base class private: };
2
3684
by: Florian Loitsch | last post by:
hi, What should be the output of the following code-snippet? === var x = "global"; function f() { var x = 0; eval("function x() { return false; }"); delete x; alert(x); }
4
2492
by: yuanhp_china | last post by:
I define a class in A.h: template <class Tclass A{ public: void get_elem( const T&) ; };
0
9685
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9535
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
10465
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
10242
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
5453
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
5582
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4127
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3744
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2931
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.