JavaScript - Class Inheritance Problem - Use Of Arrays In Derived Class
Hello,
I am new with Javascript and running into this problem that I don't understand. I define a base class that only contains an array "elements", and a derived class that contains nothing more (for simplicity): Code: function baseClass() { this.elements = new Array; } function derivedClass() { } derivedClass.prototype = new baseClass; Then I create two instances of the derived class, and add two elements in each: Code: a = new derivedClass(); a.elements.push("A"); a.elements.push("B"); b = new derivedClass(); b.elements.push("C"); b.elements.push("D"); When I examine the contents of these arrays, I see that both a.elements and b.elements contain {"A","B","C","D"} ! I.e. as if the two arrays are in fact the same array! But these are two separate instances of the class, I expect two separate arrays. Note that if instead I use the base class: Code: a = new baseClass(); a.elements.push("A"); a.elements.push("B"); b = new baseClass(); b.elements.push("C"); b.elements.push("D"); then I get a.elements = {"A","B"} and b.elements = {"C","D"}, as I would expect. Could someone explain to me the problem with using the derived class? Thank you, Stephanos Similar TutorialsI have created a class providing various functions called BaseBrowser and the class definition by using prototype. Specific browser implementations are then acheived by extending BaseBrowser (eg as 'FF' for Firefox) as shown below. The window alert(); function is overridden for alternate message box popup (using layers in the same window). The function 'browser.customAlert()' can be called from either any code or an actual 'alert()' function. However whenever it is called the value of 'someVar' as defaulted back to the new instance value of false despite the instance 'browser' having already set it to true as it were a new instance. Why is this occuring as it should remember its state between function calls ? Code: var browser; function BrowserBase(){ //instance variables this.someVar=false; function customAlert(){ this.someVar=true; // . . . other custom alert code } } function browserLink(){ BrowserBaseFF2p0.prototype=new BrowserBase();//inherit BrowserBaseFF2p0.prototype.constructor=BrowserBase; browser=new BrowserBaseFF2p0(); } function BrowserBaseFF2p0(){ BrowserBase.call(this);//call parent constructor //override generic functions for enhancement if(document.getElementById){ window.alert=function(txt){ browser.customAlert(txt); } } } I've written a javascript class that displays a popup, but as soon as the code executes the popup vanishes. I've stepped through the code, line by line and there's nothing that "hides" the popup, the DIV that is created by the class, just reverts back to the default configuration generated by the following function: Code: function generateMarkup() { //build markup var newNode = document.createElement( 'DIV' ); newNode.id = IDs.HelpPopup; newNode.style.visibility = 'hidden'; newNode.innerHTML = [ '<div id="popup">', '<div id="inside">', '</div>', '</div>' ].join( '' ); return newNode; } All the changes made to the DIVs via document.getElementById code is completely wiped out. For example: Code: document.getElementById("inside").innerHTML = sText; If I stop processing just before the Class returns to the form, the generated code is exactly as I expect it to be with all the dynamic modifications. The class is triggered by an onClick event on a BUTTON. I've tried to put a "sleep" function in after executing the function that modifies the DIVs, but that seems to execute before the function, not after, so the popup just flickers into existence and then vanishes. Can anyone give me any hint(s) as to how to stop this happening. If the value is negative it should be in red, otherwise it should be in green. It looks like JavaScript completely ignores the css class. Help please. Code: <html> <head> <title>Prva</title> <style type="text/css"> span.Pozitivno { color:green; font-weight:bold; } span.Negativno { color:red; font-weight:bold; } </style> <script type="text/javascript"> function vpisi_stevila() { var a; var b; //Vnos spremenljivk a=prompt("Vnesi stevilo a:") b=prompt("Vnesi stevilo b:") a=a*1 //S tem spremenimo string v int b=b*1 //Izpis stevil if(a<0) { document.write("A:<span class='Negativno'> " + a + " </span> <br />"); } else { document.write("A:<span class='Pozitivno'> " + a + " </span> <br />"); } if(b<0) { document.write("A:<span class='Negativno'> " + a + " </span> <br />"); } else { document.write("A:<span class='Pozitivno'> " + a + " </span> <br />"); } document.write("Vsota:", a+b, "<br />"); document.write("Razlika:", a-b, "<br />"); document.write("Mnozenje:", a*b, "<br />"); document.write("Deljenje:", a/b, "<br />"); document.write("Ostanek:", a%b, "<br />"); if(a>b) //Ce je A vecje od B { document.writeln("A je <b>večje </b> od b") } if(a<b) //Ce je B vecje od A { document.writeln("A je <b>manjse </b> od b") } if(a==b) //Ce sta enaka { document.writeln("A je <b>enako </b> b") } } </script> </head> <body onload="vpisi_stevila()"> </body> </html> What are the benefits of prototypal inheritance over classical inheritance?
What are the benefits of prototypal inheritance over classical inheritance?
First class: Code: function ClassOne(){ this.events = []; this.executeEvents = []; this.addEvents = function(event){ this.events.push(event); } this.addExecuteEvents = function(e){ this.executeEvents.push(e) } this.getEvents = function(){ return this.events; } } Second class: Code: function ClassTwo(){ this.add = function(e){ this.addEvents(e) } } ClassTwo.prototype = new ClassOne Here the second class extends the first class, now I want to create two objects of class two, Code: var b = new ClassTwo(); b.add('hello'); var c = new ClassTwo(); c.add('hi'); console.log(c.getEvents()) I just added one event on b and c each, but when I logged the c.getEvents(), it returns both 'hi' and 'hello' events. why?? What am I doing wrong?? how to solve this problem?? Thanks in advance Hi all, On my site each page is composed by header, contents and bottom. Each part, located respectively at header.php, content1.php, content2.php, ... and bottom.php, is included in page.php. I have a menu, that is the same for all pages, on header.php: Code: <ul class="site-nav"> <li><a href="home.php" class="" name="Home"></a></li> <li><a href="page2.php" class="" name="OK"></a></li> </ul> I'd like to set a class in order to have its corresponding menu with this class="act" for each content.php. I tried this but it doens't work: I add this in content1.php Code: <!-- act for site-nav --> <script language="javascript" type="text/javascript">function changeClass() { document.getElementByName("Home").setAttribute("class", act); } </script> and this in top.php Code: <ul class="site-nav"> <li><a href="home.php" class="changeClass()" name="Home"></a></li> <li><a href="page2.php" class="changeClass()" name="OK"></a></li> </ul> Please help me, I don't understand anything of javascript . Alright I have never really created a class before and I have to for a project. This is what I have so far and I will try to explain the requirements I am looking for thoroughly and what problems I am having. Code: <!doctype html public "-//w3c//dtd html 4.0 transitional//en"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> </head> <script language="javascript" type="text/javascript"> function clock () { //Object Constructor this.setT = function() { //Method Set Time //Properties this.currentTime = new Date ( ); this.currentHours = this.currentTime.getHours ( ); this.currentMinutes = this.currentTime.getMinutes ( ); this.currentSeconds = this.currentTime.getSeconds ( ); } clock.prototype.displayTime = function () { clock.setT } } </script> <body> <form name="form1"> <p> <input type="text" rows=7 cols=60 name="currentTime"> <br> <input type="button" value="Set Time" onClick="clock.displayTime();"> <br> <input type="button" value="Display Time" onClick="currentTime.value= completeTime;"> <br> <input type="reset" value="Reset"> </p> </form> </body> </html> The clock class contains: Three Properties: Hours Minutes, Seconds Two Methods setTime (which uses date class to get current time) Must be defined in the constructor displayTime (returns a string displaying current time) Must be defined as a prototype property of constructor The below is a very rough outline, and probably not correct. I've been reading up on objects for the last few hours and can't be very sure of anything yet. Code: function clock() { this.currentTime = new Date ( ); var currentHours = currentTime.getHours ( ); var currentMinutes = currentTime.getMinutes ( ); var currentSeconds = currentTime.getSeconds ( ); this.setTime = function() { } } clock.prototype.displayTime = function ( ) { } I guess my biggest problem now is the outline. Any help would be great hopefully once i get what goes where i can actually start writing the code. I already have the full code to write a basic clock just like this but it doesn't use classes or any of this. So, I have this javascript that works just fine... But... PHP Code: <script language="javascript"> function addBtn() { element = document.createElement("input"); element.setAttribute("type", 'button'); element.setAttribute("value", 'Track'); element.setAttribute("name", 'element'); element.onclick = function() { alert("Tracking"); }; var btn = document.getElementById("gs-track-btn"); btn.appendChild(element); } </script> <div id="gs-track-btn"></div> How would I target that div if the " gs-track-btn " id was a class? hey I want to get the href via attributes of this a tag & then this href to be set to a variable Hello everybody. For the moment im locking for a JavaScript-document. That will be working like this... When we are push on a link, for example to username. So will it coming up a box "<div class="profile_class"></div> From to beeing visibility: hidden; display: none; To be visibility: visibile; display: block; .profile_class { float: left; width: 300px; height: 250px; margin-top: 2px; margin-left: 2px; position: absolute; visibility: hidden; display: block; background-color: #151515; } .profile_class_inactive { visibility: visible; display: none; } When we are push on the mouse outsite the "profile_class" will it beeing closing/invisbile. But when we have it active something like "profile_class" so will it show uz... <ul> <li>Send a message</li> <li>Add contact</li> <li>Block the contact</li> </ul> And on the right site, will it beeing showing uz a little avatar. Can you please help me with this one? Hi, I need to change my class, but this isn't doing it for me and I don't see why. No error messages, but nothing happens. Code: .myClass { background-color: yellow; } document.getElementById("myId").setAttribute("class","myClass"); Thank You in Advance for Your Help, Lou I'm a amateur and I've just coded this little script. What it does is quite simple, once you click on the 'theBox' div, it switches from one class to another. I can't help having the feeling that this could have been coded in a lot more simple way than the way I've coded. So I thought that maybe you guys could help me out. (Oh, and by the way, the script works fine in FireFox and IE). Code: <script> function setDivClassName(string){ document.getElementById("divClassName").innerHTML = string; } function theBoxOnClick(){ var classes = new Array(); classes[0] = 'zero'; classes[1] = 'one'; classes[2] = 'two'; var currentClassName = document.getElementById('theBox').className; var currentClassIndex; var nowGoTo; for(var i = 0;i <= classes.length-1;i++){ //alert(classes[i]); if(classes[i] == currentClassName){ currentClassIndex = i; nowGoTo = currentClassIndex + 1; } } if(classes[nowGoTo] == undefined){ nowGoTo = 0; } document.getElementById('theBox').className = classes[nowGoTo]; setDivClassName(classes[nowGoTo]); } </script> <style> .zero{width:100;height:100;background-color:black;color:white;padding:10;border-style:solid;border-color:red;border-width:2} .one{width:100;height:100;background-color:yellow;color:red;padding:10;border-style:solid;border-color:red;border-width:2} .two{width:100;height:100;background-color:red;color:yellow;padding:10;border-style:solid;border-color:red;border-width:2} </style> <body onLoad="setDivClassName('zero')"> <div id="theBox" class="zero" onClick="theBoxOnClick()"> This DIV's Class is <div id="divClassName"></div> </div> Hello, Let's say I have a <div class="main1 secondary">. Is there an easy way to change "main1" to "main2" and make sure it is the first class? I was thinking about using jquery with .removeClass and .addClass but addClass adds it to the end. Any help would be great! Thanks I'm trying to get a div that is contained within another div to show using jQuery. Basically something like Code: jQuery(document).ready(function(){ $('.outerdiv .innerdiv').show(); }); The only problem is that the first div class isn't always the same, it depends on the URL. I have already set it up so that a var is defined based on the URL, but what I am having trouble with is using that in the show() command. So let's say my var is called "name". I would want to be able to write something sorta like $('.[name] .innerdiv').show(); so that, if the value of the var is (for instance) "jack", it would be as if I wrote $('.jack .innerdiv').show(); but I can't figure out how to properly reference the var within those quote marks. Any help? Hi I have been working at this for a while now but can't seem to figure out how to do it. What I want to do is have a class which i have done and lets say the class is called ABC so eventhing inside that would need to have ABC.test(); but what I want is to have something like ABC.test.create() where test is the sub class and I want the create function only work if the sub function is test, if that makes sence, so if the code was ABC.create() the it wont work because the subclass 'test' hasnt been called. The codes I have done at the moment a Code: function ABC(){ this.test=function(){ this.create=function(){ // code \\ } } } //////////////////////////////////////// function ABC(){ this.test=function(){ this.test.create=function(){ // code \\ } } } //////////////////////////////////////// function ABC(){ var test; this.test.create=function(){ // code \\ } } //////////////////////////////////////// function ABC(){ var test = this.test; this.test.create=function(){ // code \\ } } But none of them have worked, if anyone knows how i can do this please help, thank you! hi all, I am using ajaxcontent javascript to load content into certain parts of the website and all my links work that way.. the problem with that is that I can't use classical approach for building menus.. like when you assign "current " class to your link and then it changes color or whatever when you follow link to another html or whichever website. So I have menu like this .. Code: <li class="current"><a href="index.htm"><b>One</b></a></li> <li><a href="javascript:ajaxpage('2.php', 'right');"><b>Two</b></a></li> <li><a href="javascript:ajaxpage('3.php', 'right');"><b>Three</b></a></li> <li><a href="javascript:ajaxpage('4.php', 'right');"><b>Four</b></a></li> <li><a href="javascript:ajaxpage('5.php', 'right');"><b>Five</b></a></li> I'm sorry for my English is so bad.. but I will try to explain what I'd like to achieve.. I'd like to put in some kind of onclick script which will change class of that <li> to current but at the same time I want to change <li class="current"> to <li class=""> or <li class="whatever">... so here I go again.. Code: <li class="current"><a href="index.htm"><b>One</b></a></li> <li><a href="javascript:ajaxpage('2.php', 'right');"><b>Two</b></a></li> <li><a href="javascript:ajaxpage('3.php', 'right');"><b>Three</b></a></li> <li><a href="javascript:ajaxpage('4.php', 'right');"><b>Four</b></a></li> <li><a href="javascript:ajaxpage('5.php', 'right');" onclick="this.className='current'"><b>Five</b></a></li> Now this changes the <li> class to current and I only want to have 1 current. In this case link "Five" should have current class others should have no class or class="whatever" its same Thank you for any answers in advance I currently have a navigation bar with CSS. It sits by itself in a frame so it doesn't change with the other page turns. So I'm trying to figure out how to set each link class="active" since it always stays on the same page. I'm thinking javascript will be my friend. Is there an onclick function that can be defined? I'm not new to webpages but new to learning javascript, instead of borrow someone's code. I didn't know how to approach this code because I think I need it to say: If Onclick, then set to class="active", otherwise (then), set class="nothing" or anything to this regard. I was not sure how I could approach that code and how to fit into the UL/LI html code I currently have setup as well as the head code. Example code: (I have 3 frames called head, form, and body. Head is the nav bar where this code sits.) Code: <ul class="menu"> <li><a href="choose.htm" class="active"><span>Home</span></a></li> <li><a href="search.htm" target="form" onClick="top.body.location='http://www.google.com';"><Span> Google</span></a></li></ul> With my CSS code, the "menu" defines some colors/setup, as so does Span and class="active". As a bonus, if you could teach me instead of just help me, it would help me help others. Hey, I currently have my menu on a web page set out using the following method: Code: <div class="linkbox" onmouseover="this.className='linkbox2'" onmouseout="this.className='linkbox'" onclick="location.href='http://www.upthegame.net/';"> General Chat </div> I was wondering if there was a way using javascript to set ALL <div>'s with the class name "linkbox" to change to the class name "linkbox2" onmouseover and return to "linkbox" onmouseout. I would like this to be in a seperate file, I'm guessing this would probably be within an onload function or something along those lines. I'm only familiar with basic JS so please go easy on me Any help is much appreciated. Thanks, Tom. I wanted to design and implement a program that accepts from the user the numerator and denominator of a fraction and prints the simplified form of the fraction. So basically have TWO objects of the Fraction Class. The output line should look something like this: The fraction 3615/7230 simplifies to 1/2. but then I was wondering if it was possible to place it in a box-like look. So something like this... Sample output: *--------------------------------------* *The fraction 3615/7230 simplifies to 1/2.* *--------------------------------------* *---------------------------------* *The fraction 5/10 simplifies to 1/2.* *---------------------------------* so the box should fit with words. |