473,396 Members | 2,076 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

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=="start"){
//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.initialized == "undefined"){
Timer.prototype.startTimer = function (){
this.stopTimer();
this.counterStatus();
}
Timer.prototype.stopTimer = function (){
if(timerRunning != null){
clearTimeout(timerID);
this.timerRunning = false;
secs = 10;
}
}
Timer.prototype.counterStatus = function (){
if (secs==0){
this.stopTimer();
document.getElementById("id_" + name).style.backgroundColor = "green";
}else{
secs = secs - 1;
timerRunning = true;
document.getElementById("id_" + name).innerHTML = secs;
timerID = self.setTimeout(name + ".counterStatus()", delay);
}
}
Timer.initialized = true;
}
}

</script>
<div id="id_tmp" style="width:100px; height:100px; background-color:blue;" onmouseover="setTimer('','tmp')" onmouseout="setTimer('start','tmp')"" />
Dec 17 '05 #1
8 1631
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=="start"){
//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.initialized == "undefined"){
Timer.prototype.startTimer = function (){
this.stopTimer();
this.counterStatus();
}


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=="start"){
Timer[divId] = new Timer(divId);
Timer[divId].startTimer();
}
}

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

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

Timer.prototype = {

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

stopTimer : function (){
if(this.timerRunning != null){
clearTimeout(this.timerID);
this.timerRunning = false;
this.secs = 10;
}
},

counterStatus : function (){
var elm = document.getElementById("id_" + this.name);
if (!elm) return;
if (this.secs==0){
this.stopTimer();
elm.style.backgroundColor = "green";
}else{
this.secs--;
this.timerRunning = true;
elm.innerHTML = this.secs;
this.timerID = setTimeout("updateTimer('" + 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=="start"){
//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.initialized == "undefined"){
Timer.prototype.startTimer = function (){
this.stopTimer();
this.counterStatus();
}


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=="start"){
Timer[divId] = new Timer(divId);
Timer[divId].startTimer();
}
}

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

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

Timer.prototype = {

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

stopTimer : function (){
if(this.timerRunning != null){
clearTimeout(this.timerID);
this.timerRunning = false;
this.secs = 10;
}
},

counterStatus : function (){
var elm = document.getElementById("id_" + this.name);
if (!elm) return;
if (this.secs==0){
this.stopTimer();
elm.style.backgroundColor = "green";
}else{
this.secs--;
this.timerRunning = true;
elm.innerHTML = this.secs;
this.timerID = setTimeout("updateTimer('" + 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.stopTimer();this.counterStatus();}, //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.timerRunning = false;
this.delay = 1000;
Timer[name] = this;
}

Timer.prototype = {

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

stopTimer : function (){
if(this.timerRunning != null){
clearTimeout(this.timerID);
this.timerRunning = false;
this.secs = 10;
}
},

counterStatus : function (){
var elm = document.getElementById("id_" + this.name);
if (!elm) return;
if (this.secs==0){
this.stopTimer();
elm.style.backgroundColor = "green";
}else{
this.secs--;
this.timerRunning = true;
elm.innerHTML = this.secs;
this.timerID = setTimeout("updateTimer('" + 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.timerRunning = false;
this.delay = 1000;
Timer[name] = this;
this.startTimer = function() { ... }
this.stopTimer = function() { ... }
this.counterStatus = 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.com> writes:
While I digest your code I was wondering what kind of statement/form is this:

Timer.prototype = {startTimer : function (){this.stopTimer();this.counterStatus();}, //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/rasterTriangleDOM.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.timerRunning = false;
this.delay = 1000;
Timer[name] = this;
this.startTimer = function() { ... }
this.stopTimer = function() { ... }
this.counterStatus = 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.stopTimer();this.counterStatus();}, //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.prototype." 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
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...
8
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...
4
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...
4
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...
1
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
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...
9
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,...
3
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...
5
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: ...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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...
0
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...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...

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.