JavaScript - Confused About 'this.constructor.superclass'
Hi - In am learning Javascript and trying to understand why,
the following line : Code: arguments.callee.superclass cannot be replaced by : Code: this.constructor.superclass In the following code sample : ( the explanation given is that if someone creates a subclass of PositionedRectangle, then this.constructor will refer to the new subclass constructor, not to PositionedRectangle - but why? 'this' here to my knowledge represents the object 'PositionRectangle' and if not I can't understand why not. ) Code: // Here is a simple Rectangle class. // It has a width and height and can compute its own area function Rectangle(w, h) { this.width = w; this.height = h; } Rectangle.prototype.area = function( ) { return this.width * this.height; } // Here is how we might subclass it function PositionedRectangle(x, y, w, h) { // First, invoke the superclass constructor on the new object // so that it can initialize the width and height. // We use the call method so that we invoke the constructor as a // method of the object to be initialized. // This is called constructor chaining. PositionRectangle.superclass = Rectangle; arguments.callee.superclass .call(this, w, h); // Now store the position of the upper-left corner of the rectangle this.x = x; this.y = y; } // Create a prototype for the subclass that inherits from the prototype // of the superclass. function heir(p) { function f(){} f.prototype = p; return new f(); } PositionRectangle.prototype = heir(Rectangle.prototype); PositionRectangle.prototype.constructor = PositionRectangle; Similar Tutorialshi, i'm currently stumped by the following code. what's the point of using x.constructor.prototype? (highlighted in red) why not directly use x.prototype.classname to check whether 'classname' property is in this class? thx in advance Code: function getType(x) { // If x is null, return "null" if (x == null) return "null"; // Next try the typeof operator var t = typeof x; // If the result is not vague, return it if (t != "object") return t; // Otherwise, x is an object. Use the default toString( ) method to // get the class value of the object. var c = Object.prototype.toString.apply(x); // Returns "[object class]" c = c.substring(8, c.length-1); // Strip off "[object" and "]" // If the class is not a vague one, return it. if (c != "Object") return c; // If we get here, c is "Object". Check to see if // the value x is really just a generic object. if (x.constructor == Object) return c; // Okay the type really is "Object" // For user-defined classes, look for a string-valued property named // classname, that is inherited from the object's prototype if ("classname" in x.constructor.prototype && // inherits classname typeof x.constructor.prototype.classname == "string") // its a string return x.constructor.prototype.classname; // If we really can't figure it out, say so. return "<unknown type>"; } I need to detect the "name" of the constructor of an object. For example, myArray.constructor === Array is true, but I want something where that === 'Array' is true. I've heard of Object.constructor.name, but it's not widely compatible. Any ideas (preferably without involving regular expressions)? Thanks in advnce, Julian I had read from books that the constructor property of object is inherited from its prototype. And the prototype can be changed dynamically. New property can be added to or deleted from object even it was created before the prototype change. But I got confused on below codes. Code: function A() { this.title = "A"; } function B() { this.title = "B"; } document.write("<br>"); var b = new B(); document.write(b.constructor); document.write("<br>"); document.write(B.prototype.constructor); document.write("<br>"); B.prototype = new A(); document.write(b.constructor); // Suppose to output "function A() ..." document.write("<br>"); document.write(B.prototype.constructor); document.write("<br>"); B.prototype.constructor = B; document.write(b.constructor); document.write("<br>"); document.write(B.prototype.constructor); document.write("<br>"); But the actual result (both IE and firefox) is Code: function B() { this.title = "B"; } function B() { this.title = "B"; } function B() { this.title = "B"; } function A() { this.title = "A"; } function B() { this.title = "B"; } function B() { this.title = "B"; } Please help me. thanks. I have a dice simulator. Basically, a user enters how many sides they want on their die, and then I digitally roll 2 of them. And produce the output in a document.writeln. I think I'm having trouble with the this.sides in the constructor function (in the head section). Also, I'm getting a syntax error in Safari : 25TypeError: 'null' is not an object (evaluating 'element.value') Am I not suppose to put the variable in the constructor function? Any help would be appreciated. <head> var element = document.getElementById("number"); var sides = element.value; function Die( ) { this.sides = sides; this.roll = function( ) { return parseInt((Math.random( ) * 1000) % this.sides) + 1; } } </script> </head> <body> <h1>Adam's Dice Rolling Game!</h1><br/> <form action="" method="post"> <p> <input type="text" name="number" id="number"/> </p> <p> <input type="button" value="Roll the dice!" id="roll_me"/> </p> </form> <script type="text/javascript"> var d = new Die( ); d.sides = sides; var rolled_value = d.roll( ); var r1 = document.getElementById( "roll_me" ); r1.onclick = function Die () { document.writeln ( d.roll () ); } </script> How to extend the constructor for the date object of the javasccript so that whenever a call is made to the constructor, I want to perform a particular action? Basically how to define wrappers for default javascript methods or objects like Date() so that I can perform some action and then invoke the original method? So basically if I have something like var a = new Date(); I want it to (say) alert the value of the date everything Date() is called and then execute the default date constructor. TIA I am trying to understand why I had an error, or why my solution worked. In my HTML I had: Code: <script language="JavaScript" type="text/javascript" src="Book.js"></script> <script language="JavaScript" type="text/javascript" src="Book_TEST.js"></script> Book.js said: Code: function Book(title, author) { this.title = title; this.author = author; } Book.prototype.toString = function() { return '"' + this.title + '" by '+ this.author; }; var Book = new Book ("John", "Dough"); alert (Book); // displays "John Dough" And, predictably, at this stage, the code worked. Book.js said: Code: var myBook = new Book ("JavaScript Tutorials", "Herong Yang"); However, at this point the JavaScript would crash and I'd get an error "Error: Book is not a constructor javascript." I drove myself nuts trying to figure out why the code wasn't working at this later point. Eventually, I copied another object: Code: /* * Person class */ /** * Person constructor * * @param {String} first * The person's first name * @param {String} last * The person's last name */ function Person(first, last) { this.first = first; this.last = last; } /** * Create a string representation of this object * * @return {String} A string representation of this object */ Person.prototype.toString = function() { return this.first + " " + this.last; }; /* var person = new Person ("John", "Dough"); alert (person); // displays "John Dough" */ and then used find and replace to swap {Person, first, last} with {Book, title, author}, resulting in: Code: /* * Book class */ /** * Book constructor * * @param {String} title * The Book's title * @param {String} author * The Book's author */ function Book(title, author) { this.title = title; this.author = author; } /** * Create a string representation of this object * * @return {String} A string representation of this object */ Book.prototype.toString = function() { return '"' + this.title + '" by '+ this.author; }; var Book = new Book ("John", "Dough"); alert (Book); // displays "John Dough" Now, the code worked fine in both script. (i.e., no more error.) So far as I can tell, the only differences between the first and next version of Book.js are the comments and the whitespace. Am I missing something? Can the comments or whitespace somehow effect the logic with which this code has been executing? If I get an error like this again, is there an easier/better way to fix it than to essentially retype the code? Thanks in advance for helping me to understand this. Hi All, Why is the Option constructor converting my text as follows? text = ' 1:30 pm' Option tag that gets generated: <option value="10">&nbsp;&nbsp;1:30 pm</option> How do I suppress the conversion of the & to & by the constructor? I've tried escaping the & but that's a no go. Thanks in advance for any help on this. JD ----------SOLUTION---------- ----------ORIGINAL PROBLEM---------- The second line of code. What does it do? It's confusing because it doesn't have a semicolon at the end and it doesn't end with (). Code: var centreicon = new GIcon(); centreicon.constructor centreicon.image = "http://maps.google.com/mapfiles/kml/pal3/icon31.png "; centreicon.shadow = "http://maps.google.com/mapfiles/kml/pal3/icon31s.png "; centreicon.iconSize = new GSize(12, 20); centreicon.shadowSize = new GSize(22, 20); centreicon.iconAnchor = new GPoint(6, 20); centreicon.infoWindowAnchor = new GPoint(5, 1); I found this on stackoverflow while trying to find a way to make my own icons on a map. With that being said. I'm still confused about how to apply the new graphic to a map. I don't see how they apply that picture to a coordinate. Does anyone know how to do that? Can I do this? Code: var centreicon = new GIcon(); centreicon.constructor centreicon.image = "http://maps.google.com/mapfiles/kml/pal3/icon31.png "; centreicon.shadow = "http://maps.google.com/mapfiles/kml/pal3/icon31s.png "; centreicon.iconSize = new GSize(12, 20); centreicon.shadowSize = new GSize(22, 20); centreicon.iconAnchor = new GPoint(6, 20); centreicon.infoWindowAnchor = new GPoint(5, 1); var marker = new GMarker( new GLatLng(-34.397, 150.644) , centreicon); map.addOverlay(marker); -------- A tad bit later -------- So this is the code I have on my testing site Even thought I'ved defined the the icon's image and location It does not show up on the map. What am I missing? Code: <!DOCTYPE html> <html> <head> <meta name="viewport" content="initial-scale=1.0, user-scalable=no" /> <style type="text/css"> html { height: 100% } body { height: 100%; margin: 0; padding: 0 } #map_canvas { height: 100% } </style> <script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?key=AIzaSyAWhjy3iZ8g6BZszj299c0yUY6ahKpSr1U&sensor=false"> </script> <script type="text/javascript"> function initialize() { var myOptions = { center: new google.maps.LatLng(-34.397, 150.644), zoom: 8, mapTypeId: google.maps.MapTypeId.ROADMAP }; var map = new google.maps.Map(document.getElementById("map_canvas"),myOptions); var centreicon = new GIcon(); centreicon.constructor centreicon.image = "http://maps.google.com/mapfiles/kml/pal3/icon31.png "; centreicon.shadow = "http://maps.google.com/mapfiles/kml/pal3/icon31s.png "; centreicon.iconSize = new GSize(12, 20); centreicon.shadowSize = new GSize(22, 20); centreicon.iconAnchor = new GPoint(6, 20); centreicon.infoWindowAnchor = new GPoint(5, 1); var marker = new GMarker( new GLatLng(-34.397, 150.644) , centreicon); map.addOverlay(marker); } </script> </head> <body onload="initialize()"> <div id="map_canvas" style="width:100%; height:100%"></div> </body> </html> var n = 123456.789; n.toFixed(0); just starting out JavaScript. So i type the above code in firebug. it returns this result:- "123457" As for as i know, toFixed() converts a number to a string with a specified number of digits after the decimal point. If i have specified 0, which i'm assuming it means 0 digits after the decimal point, why does the 7 appear and the 6 is taken out. really fustrating and can't seem to get my head over it. Hey i got this code and i looked at it and im so lost i cant describe it can someone hep me in understanding the ins and outs of this. Code: var YOOaccordion=new Class({initialize:function(togglers,elements,options){this.setOptions({open:'first',allowMultipleOpen:false,fade:false,fadeDuration:600,transition:Fx.Transitions.linear,duration:400},options);this.togglers=togglers;this.elements=elements;this.elementFx=[];this.elementVisible=[];this.togglers.each(function(tog,i){tog.addEvent('click',function(){this.toggleSection(i)}.bind(this))},this);this.elements.each(function(el,i){this.elementFx[i]=new Fx.Slide(el,this.options);if(!(this.options.allowMultipleOpen&&this.options.open=='all'))this.hide(i)},this);if(this.options.open=='first')(function(){this.slideIn(0)}).delay(1,this)},toggleSection:function(iToToggle){if(!this.options.allowMultipleOpen){this.elements.each(function(el,i){if(this.elementVisible[i]&&i!=iToToggle)this.slideOut(i)},this)}this.toggle(iToToggle)},toggle:function(i){this.elementFx[i].toggle().chain(function(){this.elementVisible[i]=(this.elementVisible[i]+1)%2}.bind(this));if(this.options.fade)this.fade(i)},slideIn:function(i){this.elementFx[i].slideIn().chain(function(){this.elementVisible[i]=1}.bind(this));if(this.options.fade)this.fade(i)},slideOut:function(i){this.elementFx[i].slideOut().chain(function(){this.elementVisible[i]=0}.bind(this));if(this.options.fade)this.fade(i)},show:function(i){this.elementVisible[i]=1;this.elementFx[i].show()},hide:function(i){this.elementVisible[i]=0;this.elementFx[i].hide()},fade:function(i){var fx=new Fx.Styles(this.elements[i],{'duration':this.options.fadeDuration,'wait':false});fx.start({'opacity':[this.elementVisible[i],(this.elementVisible[i]+1)%2]})}});YOOaccordion.implement(new Options); I trying to display a random number using innerHTML Here's my code: Code: <html> <head> <script language="JavaScript"> var myArray = new Array("String1", "String2", "String3", "String4", "String5", "String6", "String7", "String8", "String9", "String10"); var num = Math.floor(myArray.length * Math.random()); document.writeln(myArray[num]); //document.getElementById("myString").innerHTML = myArray[num]; </script> </head> <body> <div id="myString"></div> </body> </html> it works when I use document.writeln(myArray[num]); but does NOT work for document.getElementById("myString").innerHTML = myArray[num]; any ideas?? tks First let me say, I do know how to code I just haven't for a VERY long time and things are slow to come back. That being said, I'm working on a self induced project to bring back my coding abilities and I'm stuck. What I'm wanting to happen is when a certain link is clicked it goes to a certain photo album and pulls random pics just from that album and displays them in a certain place on that page. What would be the best way to approach this to make it happen? I'm not wanting someone to do this for me, just get me going in the right direction. Thanks.... I'm picking up some work on a site that has been built already in joomla! On some of the pages IE is breaking it and pushing it down to the bottom. example:LINK TO BREAKAGE That Volleyball tag should be up next to the picture. And there is an entire paragraph underneath that that is not getting seen. Someone told me at first that it was the javascript, and I thought it was the Rokbox plugin, but that's not even activated. I am so confused. And it's not the css, because I tried that. Has anyone else experienced this problem? And how is it fixed? I have been working on it all weekend! Thank you for all comments! The situation: I have a javascript scroller that loads it's data via JQuery .load function (code not listed as it is not relevant to the problem.) The amount of data loaded is greater than what is shown (each piece of data in it's own div with id's from #scroller1 to #scroller20). So you can see the first 13 div's right away and the other 7 are scrolled in 1 by one as the first 7 are scrolled out 1 by 1 in an endless and consecutive loop. The problem: For some reason, after div20 (#scroller20) is scrolled in to view, my scroller removes div8 but does not add div1 creating a blank space below div9 (if this confuses you, take a look at the link at the bottom of this post.) After div20 is removed, then div13 is added but div1 is NOT removed, now filling this blank space. Now normally this is not visible to be a problem, except that each of these div's will end up being much higher, perhaps only 4 showing at a time, so when one of these 4 disappears, then reappears, it will become unacceptable. Why is this happening? I am sure it has to the code/math inside of function divage... but I can't figure it out for some reason... please help. Here is my javascript code (which uses JQuery) Code: var slide = 1; var auto_scroll = setInterval("scrollme(slide++)", 4000); function scrollme(i){ divage(i); } function divage(i){ removeIt(i%21); addIt((i+13)%21); var j=((i-1)%21); $('#scroller-main-text').prepend($("#scroller"+j)); } function addIt(i){ $("#scroller"+i).fadeIn(1000); } function removeIt(i){ $("#scroller"+i).fadeOut(500); } URL where the problem can be witnessed: http://www.inspiritandintruth.com Hi, thanks for reading this. I have two templates that I use on my website that use font faces.....(both of these templates were free downloads). However, if I look at the files for each of these templates, they use font face differently - can someone kindly check if they are ok? Is one wrong and one right? Template 1: Which works 100% well in all browsers There is NO css reference, rather, each page has this javascript: <script type="text/javascript" src="../jsfunnels/cufon-yui.js"></script> <script type="text/javascript" src="../jsfunnels/MgOpen_Moderna_700.font.js"></script> <script type="text/javascript" src="../jsfunnels/Chunk_400.font.js"></script> <!-- Start Video section --> <script type="text/javascript"> Cufon.replace('h1', { fontFamily: 'Chunk' }); Cufon.replace('h2', { fontFamily: 'Chunk' }); Cufon.replace('h3', { fontFamily: 'Chunk' }); Cufon.replace('h7', { fontFamily: 'Chunk' }); Cufon.replace('h4', { fontFamily: 'MgOpen Moderna' }); Cufon.replace('h6', { fontFamily: 'MgOpen Moderna' }); </script> Template 2: Which works 70% well in all browsers <script type="text/javascript" src="js/cufon-yui.js"></script> <script type="text/javascript" src="js/TitilliumMaps26L_500.font.js"></script> <script type="text/javascript" src="js/TitilliumMaps26L_300.font.js"></script> <script type="text/javascript" src="js/jquery.js"></script> <script type="text/javascript" src="js/scripts.js"></script> <script type="text/javascript"> Cufon.replace('.footer span','.footer span a',{ fontFamily: 'TitilliumMaps26L-250wt'}); Cufon.replace('.col-left p',{ fontFamily: 'TitilliumMaps26L-250wt'}); Cufon.replace('.reg a',{ fontFamily: 'TitilliumMaps26L-250wt'}); Cufon.replace('.content4-left p',{ fontFamily: 'TitilliumMaps26L-250wt'}); Cufon.replace('.content4-right p.title',{ fontFamily: 'TitilliumMaps26L-250wt'}); Cufon.replace('.header-right','.search span','.header-right ul li a',{ fontFamily: 'TitilliumMaps26L-500wt'}); Cufon.replace('h1',{ fontFamily: 'TitilliumMaps26L-500wt'}); </script> And the CSS which I believe is the culprit is he @font-face { font-family: 'TitilliumMaps26L002'; src: local('../font/TitilliumMaps26L002-250wt') url('../font/TitilliumMaps26L002.otf') format('opentype'); } ------------------ Now, according to Paul Irish article, I should NOT make the above CSS a local path - see the red font above. So I guess my questions are, can anyone see anything wrong with the above, and why is there a different approach, i.e. one uses css and the other doesn't? THANKS VERY MUCH My client has a training site that is associated with 4 different domains. If a user navigates away from one of the domains to another site (for instance www.google.com) they want to display a message and ask them if they want to leave the training site. my understanding of the window.location.href is that it will capture what is typed into the address bar until the request is submitted to the server but by then they are leaving the site. below is my code on the onbeforeunload event. conceptually: i want to capture the URL, compare the hostname and if the host name is one of the 4 domains then allow them to proceed, if it is not then as them if they want to leave the site. if they click ok allow them to move forward, if the click cancel then reload the page. I know this is considered bad design and i have expressed this but this how they want the site to behave. thanks ________________________________________________________________ [CODE] <script type="text/javascript"> function SiteCheck() { var strCurrentURL = window.location.href; var strNewHostName = strCurrentURL.split("/"); // for(i = 0; i < strNewHostName.length; i++) { alert(i + ' ' + strNewHostName[i]); } //strNewHostName[4] = "sddmtraining.org"; //test values //strNewHostName[4] == 'sddmtrain.org'; //test values //strNewHostName[4] == 'www.sddmtrain.web.org'; test values if (strNewHostName[4] == 'sddmtraining.org' || strNewHostName[4] == 'sddmtrain.org' || strNewHostName[4] == 'www.sddmtrain.web.org') ; else { var r = confirm("Are you sure you want leave the Training Site - Click Ok to Leave / Click Cancel to stay"); if (r==true) ; else { window.location.reload(window.location.href ); } } } </script> [\CODE] Hi there coding friends, im stuck again this time on arrays.. Im trying to get my head around it and im sure it's one of those things you do once you know what your doing (to an extent) now the problem is... i have 2 arrays for a experiment one = flowerheight and the other is flowernumbers. now the height is set out as 15,16,17,18,19 and numbers 2,1,6,4,2 what the aim is in the first part is to times the height by numbers of the corresponding array ie. 15x2 16x1 17x6 18x4 19x2 to make a 3rd array with them as the totals then the second part of the program is to calculate the average height i.e total of total of numbers array (2+1+6+4+2) + total of 3rd array(15x2+16x1+17x6+18x4+19x2) then a write to show what the total was.. now all I have of the code is... Code: <HTML> <HEAD> <TITLE> Flower Experiment </TITLE> <SCRIPT LANGUAGE = "JavaScript"> /* * Program to calculate average height of flowers.. */ //Experiment results var flowerHeights = [15,16,17,18,19]; var flowerNumbers = [2,1,6,4,2]; //Write code to work out and show flowerheightxnumbers. //Write code to calculate the average height of the flowers (total of flowernumbers + (flowerheight X numbers) and write it out in the browser window. </SCRIPT> </HEAD> <BODY> </BODY> </HTML> now I have no idea how to go about this it's making me loose my mind. Can someone start me off in the right directon and/or explain to me what to do. Anyhelp much appreciated, I wish I could have done more to the question to make it easier for you lot to help me but my brain is frazzled Thanks. James For a project in my high school web design class, I need to integrate an Excel spreadsheet as data so to speak for a web page. I want to pull the prices from the sheet, and make them appear on the page. I'd like to pull it from the sheet so that the client can still adjust and edit the prices without having to reach the actual webpage. Conceptually, I thought this would be fairly straight forward, but in researching how to do this, I got very confused. I'm not even positive that I'm putting this in the right section. So my main question is this: Is there a way to integrate an Excel spreadsheet in such a way that it can provide data for certain fields of a webpage? If so, can someone please explain how? Thanks, A Confused High School Girl |