473,569 Members | 2,870 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Dynamically name an instance of an Object

CES
All,
I'm sorry but I still don't get this!!

I'm trying to use a variable that is passed into a function to to dynamically name an instance of an Object(). I've created a Timer() Object that seems to work just fine... the problem is I can't figure out how to pass in an instance name into setTimer() to create a new instance of Timer() object?? My ultimate goal is to have multiple instances of the Timer() Object running at once. While the code below works it only allows me to create 1 instance of the Timer() Object with the name of tmp.

I've tried adding both:
var tmp = divId; // This is what I would like...
var tmp = "tmp"; // But even this throws an error...
But these will throw a "tmp is undefined" error and points to line 1 chr 1? Unfortunately my knowledge of JavaScript is so limited I just don't see the problem?

Any help on this wold be greatly appreciated... Thanks in advance. - CES

function setTimer(status ,divId){
//var tmp = divId; This will throws an error!!
if(status=="sta rt"){
//var tmp = divId; This will throws an error!!
tmp = new Timer(divId); // Why will var tmp = new Timer(divId); throws an error here??
tmp.startTimer( );
}else if(typeof tmp == "object"){
tmp.stopTimer() ;
tmp = ''; // Why does tmp = null; throw an error isn't object = null, the proper way of disposing of an object??
}
}

function Timer(name){
var secs = 10;
var timerID = null;
var timerRunning = false;
var delay = 1000;

if(typeof Timer.initializ ed == "undefined" ){
Timer.prototype .startTimer = function (){
this.stopTimer( );
this.counterSta tus();
}
Timer.prototype .stopTimer = function (){
if(timerRunning != null){
clearTimeout(ti merID);
this.timerRunni ng = false;
secs = 10;
}
}
Timer.prototype .counterStatus = function (){
if (secs==0){
this.stopTimer( );
document.getEle mentById("id_" + name).style.bac kgroundColor = "green";
}else{
secs = secs - 1;
timerRunning = true;
document.getEle mentById("id_" + name).innerHTML = secs;
timerID = self.setTimeout (name + ".counterStatus ()", delay);
}
}
Timer.initializ ed = true;
}
}

</script>
<div id="id_tmp" style="width:10 0px; height:100px; background-color:blue;" onmouseover="se tTimer('','tmp' )" onmouseout="set Timer('start',' tmp')"" />
Dec 17 '05 #1
8 1642
CES wrote:
function setTimer(status ,divId){
//var tmp = divId; This will throws an error!!
Well, you create a local variable and expect it to be global by
referencing it by name in your timer script

timerID = self.setTimeout (name + ".counterStatus ()", delay);
^^^^
And even it it would be a global variabel you always overwrite it here.

The statement itself will not throw any error and it's not necessary to
set a new variable to hold the same value allready given in divId.
The error was thrown by the given line (check out your script with
Firefox which will show you much more detailed and exact error messages
in it's JavaScript Console.

if(status=="sta rt"){
//var tmp = divId; This will throws an error!!
same as above.

tmp = new Timer(divId); // Why will var tmp = new
Timer(divId); throws an error here??
dito.

tmp.startTimer( );
}else if(typeof tmp == "object"){
tmp.stopTimer() ;
tmp = ''; // Why does tmp = null; throw an error isn't
object = null, the proper way of disposing of an object??
use the delete operator or at least set it to null. "" (or '') is an
empty string which is not the same as null.

function Timer(name){
var secs = 10;
var timerID = null;
var timerRunning = false;
var delay = 1000;

if(typeof Timer.initializ ed == "undefined" ){
Timer.prototype .startTimer = function (){
this.stopTimer( );
this.counterSta tus();
}


I really don't see a reason why you define the prototype methods within
the main function. This migh lead to unwanted memory leaks caused by so
called closures (A function that is defined within another function and
may reference all variables of the outer function).

Maybe something like this is what you are looking for:

function setTimer(status ,divId){
if (typeof Timer[divId] == "object" && typeof
Timer[divId].stopTimer == "function")
Timer[divId].stopTimer();
if(status=="sta rt"){
Timer[divId] = new Timer(divId);
Timer[divId].startTimer();
}
}

function updateTimer(nam e) {
if (Timer[name])
Timer[name].counterStatus( );
}

function Timer(name){
this.secs = 10;
this.name = name;
this.timerID = null;
this.timerRunni ng = false;
this.delay = 1000;
Timer[name] = this;
}

Timer.prototype = {

startTimer : function (){
this.stopTimer( );
this.counterSta tus();
},

stopTimer : function (){
if(this.timerRu nning != null){
clearTimeout(th is.timerID);
this.timerRunni ng = false;
this.secs = 10;
}
},

counterStatus : function (){
var elm = document.getEle mentById("id_" + this.name);
if (!elm) return;
if (this.secs==0){
this.stopTimer( );
elm.style.backg roundColor = "green";
}else{
this.secs--;
this.timerRunni ng = true;
elm.innerHTML = this.secs;
this.timerID = setTimeout("upd ateTimer('" + this.name+ "')",
this.delay);
}
}
};

Daniel
Dec 19 '05 #2
CES
Daniel Kirsch wrote:
CES wrote:
function setTimer(status ,divId){
//var tmp = divId; This will throws an error!!


Well, you create a local variable and expect it to be global by
referencing it by name in your timer script

timerID = self.setTimeout (name + ".counterStatus ()", delay);
^^^^
And even it it would be a global variabel you always overwrite it here.

The statement itself will not throw any error and it's not necessary to
set a new variable to hold the same value allready given in divId.
The error was thrown by the given line (check out your script with
Firefox which will show you much more detailed and exact error messages
in it's JavaScript Console.

if(status=="sta rt"){
//var tmp = divId; This will throws an error!!


same as above.

tmp = new Timer(divId); // Why will var tmp = new
Timer(divId); throws an error here??


dito.

tmp.startTimer( );
}else if(typeof tmp == "object"){
tmp.stopTimer() ;
tmp = ''; // Why does tmp = null; throw an error isn't
object = null, the proper way of disposing of an object??


use the delete operator or at least set it to null. "" (or '') is an
empty string which is not the same as null.

function Timer(name){
var secs = 10;
var timerID = null;
var timerRunning = false;
var delay = 1000;

if(typeof Timer.initializ ed == "undefined" ){
Timer.prototype .startTimer = function (){
this.stopTimer( );
this.counterSta tus();
}


I really don't see a reason why you define the prototype methods within
the main function. This migh lead to unwanted memory leaks caused by so
called closures (A function that is defined within another function and
may reference all variables of the outer function).

Maybe something like this is what you are looking for:

function setTimer(status ,divId){
if (typeof Timer[divId] == "object" && typeof Timer[divId].stopTimer
== "function")
Timer[divId].stopTimer();
if(status=="sta rt"){
Timer[divId] = new Timer(divId);
Timer[divId].startTimer();
}
}

function updateTimer(nam e) {
if (Timer[name])
Timer[name].counterStatus( );
}

function Timer(name){
this.secs = 10;
this.name = name;
this.timerID = null;
this.timerRunni ng = false;
this.delay = 1000;
Timer[name] = this;
}

Timer.prototype = {

startTimer : function (){
this.stopTimer( );
this.counterSta tus();
},

stopTimer : function (){
if(this.timerRu nning != null){
clearTimeout(th is.timerID);
this.timerRunni ng = false;
this.secs = 10;
}
},

counterStatus : function (){
var elm = document.getEle mentById("id_" + this.name);
if (!elm) return;
if (this.secs==0){
this.stopTimer( );
elm.style.backg roundColor = "green";
}else{
this.secs--;
this.timerRunni ng = true;
elm.innerHTML = this.secs;
this.timerID = setTimeout("upd ateTimer('" + this.name+ "')",
this.delay);
}
}
};

Daniel


Daniel,

While I digest your code I was wondering what kind of statement/form is this:

Timer.prototype = {startTimer : function (){this.stopTim er();this.count erStatus();}, //Other methods}

The "value : function()" makes it look like a switch but it obviously not??

I'm assuming that:
Timer.prototype = {startTimer : function(){
is equivalent to:
Timer.prototype .startTimer = function (){

Sorry for the real stupid question. Thanks in advance. - CES


Dec 19 '05 #3
Daniel Kirsch wrote:

function Timer(name){
this.secs = 10;
this.name = name;
this.timerID = null;
this.timerRunni ng = false;
this.delay = 1000;
Timer[name] = this;
}

Timer.prototype = {

startTimer : function (){
this.stopTimer( );
this.counterSta tus();
},

stopTimer : function (){
if(this.timerRu nning != null){
clearTimeout(th is.timerID);
this.timerRunni ng = false;
this.secs = 10;
}
},

counterStatus : function (){
var elm = document.getEle mentById("id_" + this.name);
if (!elm) return;
if (this.secs==0){
this.stopTimer( );
elm.style.backg roundColor = "green";
}else{
this.secs--;
this.timerRunni ng = true;
elm.innerHTML = this.secs;
this.timerID = setTimeout("upd ateTimer('" + this.name+ "')",
this.delay);
}
}
};


Is it even necessary to use the prototype object in this case? Seems to me
this type of construction should suffice:

function Timer(name){
this.secs = 10;
this.name = name;
this.timerID = null;
this.timerRunni ng = false;
this.delay = 1000;
Timer[name] = this;
this.startTimer = function() { ... }
this.stopTimer = function() { ... }
this.counterSta tus = function() { ... }
}
--
Dave Anderson

Unsolicited commercial email will be read at a cost of $500 per message. Use
of this email address implies consent to these terms. Please do not contact
me directly or ask me to contact you directly for assistance. If your
question is worth asking, it's worth posting.
Dec 19 '05 #4
CES <no**@none.co m> writes:
While I digest your code I was wondering what kind of statement/form is this:

Timer.prototype = {startTimer : function (){this.stopTim er();this.count erStatus();}, //Other methods}

The "value : function()" makes it look like a switch but it obviously not??
It's not. It's part of the notation for an object literal. It has
the form
{ name : value , name2 : value2, <etc> }
I'm assuming that:
Timer.prototype = {startTimer : function(){
is equivalent to:
Timer.prototype .startTimer = function (){


Almost, but not entirely.

In the first case, you create a new object, using an object literal
to define it, and then assigns that to Timer.prototype . That overrides
the existing value of Timer.prototye.

In the second case you merely add one property to the existing object
value of Timer.prototype . It retains its existing properties, including
Timer.prototype .constructor (with the default value Timer).

/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.'
Dec 19 '05 #5
Dave Anderson wrote:
Is it even necessary to use the prototype object in this case? Seems to me
this type of construction should suffice:

function Timer(name){
this.secs = 10;
this.name = name;
this.timerID = null;
this.timerRunni ng = false;
this.delay = 1000;
Timer[name] = this;
this.startTimer = function() { ... }
this.stopTimer = function() { ... }
this.counterSta tus = function() { ... }
}


Yes, but you create unnecessary closures (functions within a function)
again and your methods will be created for each instance you create.
Using the prototype will create the method only one time and all
instances reference that prototype method, so less memory is needed.

Daniel
Dec 21 '05 #6
CES wrote:
While I digest your code I was wondering what kind of statement/form is
this:

Timer.prototype = {startTimer : function
(){this.stopTim er();this.count erStatus();}, //Other methods}


It's the short way of defining an object with defined properties or (in
this case) methods.

Creating an Object:

var obj = new Object();

or shorter

var obj = {};

Adding properties to that object:

var obj = new Object();
obj.prop1 = "value";
obj.prop2 = 5;

or shorter

var obj = {prop1 : "value", prop2 : 5};

But not only simple properties can be set but also methods or subobjects.

var obj = {prop1 = "value",
meth1 : function(msg) {
if (msg)
alert(msg);
}
};

That's the same as using

var obj = new Object();
obj.prop1 = "value";
obj.meth = function(msg) {
if (msg)
alert(msg);
};
Using that object notation for the prototype saves a lot of typing and a
couple of characters which results in a smaller document size and
therefore can be downloaded faster. (all occurences of
"Object.prototy pe." can be avoided)

Daniel
Dec 21 '05 #7
Daniel Kirsch wrote:
var obj = {prop1 = "value",

^
This must read

var obj = {prop1 : "value",

Daniel
Dec 21 '05 #8
Daniel Kirsch wrote:
Creating an Object:

var obj = new Object();

or shorter

var obj = {};
With the (weak) provision that the latter (Object object literals) requires
JavaScript 1.3 (NN4.06), JScript 3.0 (IE4, IIS4) or an ECMAScript 3
conforming implementation (such as the Opera implementation since Opera
6.0), while the former is supported ever since.
var obj = {prop1 = "value",
You corrected this typo yourself in news:do******** *****@news.t-online.com
meth1 : function(msg) {
if (msg)
alert(msg);
}
};

That's the same as using

var obj = new Object();
obj.prop1 = "value";
obj.meth = function(msg) {

^
Typo, should be `obj.meth1'.
Regards,
PointedEars
Dec 21 '05 #9

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

Similar topics

5
1486
by: damian birchler | last post by:
Hello there! I'm wondering if it is possible to automatically dynamically add methods to a class instance. For example, if there is a class Foo with one method named add_function and an instance of Foo f - class Foo: add_function(self, name, args): # ...
8
2932
by: Kevin Little | last post by:
#!/usr/bin/env python ''' I want to dynamically add or replace bound methods in a class. I want the modifications to be immediately effective across all instances, whether created before or after the class was modified. I need this to work for both old ('classic') and new style classes, at both 2.3 and 2.4. I of course want to avoid...
4
20290
by: DotNetJunkies User | last post by:
Hi, Does anyone know how/if you can instantiate a C# reference type object dynamically? More specifically, my project has a number of classes that I've created and in some cases it would be very handy to be able to instantiate them based on a string variable representing their class name. Here's an example of what I'd be looking to do. ...
4
17010
by: Ray | last post by:
I want to dynamically load DLLs (created from VB) and instantiate a class with a particular name, like "ProcessClass". I am able to load the DLL and confirm there is a class by that name BUT I can't seem to create it or call methods to this newly created instance. I have the following code: public class Script {
1
5638
by: David J. Berman | last post by:
Thanks for any help...! My error is: Object reference not set to an instance of an object. > public int DisplayOrder { > get { >>>>>> return (int) ViewState; > }
3
2978
by: Tom | last post by:
Hi All : I'm VB.Net Beginner I try to create object Dynamically : In my testing, I create 2 .net project One is MyApp (Type is windows application) with one button name "Button1" The another one is "prj01" (Type is Class libary) with one public Class name "dbLib" In this prj01.dbLib I create the simple code "
9
1854
by: sashang | last post by:
Hi I'd like to use metaclasses to dynamically generate a class based on a parameter to the objects init function. For example: class MetaThing(type): def __init__(cls, name, bases, dict, extra_information): super(MetaThing, cls).__init__(name, bases, dict)
3
1469
by: kj | last post by:
I've tried a bazillion ways to code dynamically generated methods, to no avail. The following snippet is a very simplified (and artificial) demo of the problem I'm running into, featuring my latest attempt at this. The idea here is to use __getattr__ to trap any attempt to invoke a nonexistent method, have it return a generic handler...
5
14565
by: akonsu | last post by:
hello, i need to add properties to instances dynamically during run time. this is because their names are determined by the database contents. so far i found a way to add methods on demand: class A(object) : def __getattr__(self, name) : if name == 'test' : def f() : return 'test'
0
7922
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. ...
0
8119
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...
0
7964
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...
0
6281
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
0
5218
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3637
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2111
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
1
1209
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
936
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...

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.