JavaScript - Javascript - Accessing Object's Internal Properties
Hello everyone,
I am fairly familiar with the concept of Objects and their properties and methods, but javascript being object based as opposed to object oriented has me stumped on how to access an object's properties from an onclick event handler created for another object created within the original object. In the example below, I have a constructor function called anyObj. to which I pass an object reference to an element. anyObj has 3 properties and one function increaseWidth() increaseWidth() creates a new button with an onclick event handler and this is where I have a problem. The onclick function needs to increase the value of anyObj's this.width property. I originally had a line this.width += 10; in the onclick but quickly realised why this wasn't working because the this in the onclick function refers to the new button object and not the this.width property of anyObj. The workaround I have used, and it works, is to make a copy of all the this.xxxxx properties. eg. width = this.width; and use the width variable in the onclick as you can see below. This "workaround" works fine but doesn't feel ideal to me. So, what I am asking advice on is, is there a better way to access the anyObj()'s properties from within the onclick function than the way I have done it? Obviously I would prefer to not have to make copies of all the anyObj() properties like I have to make them accessible to the onclick function. Code: function anyObj(divObj){ this.elem = divObj; this.width = 50; this.height = 50; this.increaseWidth=function(){ width = this.width; height = this.height; //create a button for this object to be appended to an element later on var newButton = document.createElement('button'); newButton.onclick=function(){ width += 10; //... //... } //... //... } } Similar TutorialsI have developped a script in order to resize the height of a div on a web page in order to display it at least up to the size of the window. Here is the code: function resize(){ var frame = document.getElementById("content"); var padding_top = parseInt(window.getComputedStyle(frame,null).getPropertyValue("padding-top")); var padding_bottom = parseInt(window.getComputedStyle(frame,null).getPropertyValue("padding-bottom")); var padding = padding_top + padding_bottom; var bodyheight = document.body.scrollHeight; var windowheight = window.innerHeight; if (bodyheight < windowheight){ frame.style.height = windowheight - padding + "px"; } } It works well, but I was wondering why I am not able to get the padding-top and -bottom using these two instructions: var padding_top = frame.style.paddingTop; var padding_bottom = frame.style.paddingBottom; The script runs but Firebug shows empty strings for both values. How come? Is there a bug in Firefox? Thanks inadvance for your time and help. I created a method for displaying an object's properties: Code: renderfunction = false; function showProperty (object, property) { document.write ('<td class="type">' + (typeof object[property]) + '</td>' + '<td class="name">' + property + '</td>'); document.writeln('<td class="value">' + ( (typeof object[property] != 'function') ? object[property] :( (property != 'showProperties') ? ( renderfunction ? object[property]() : ('<span class="self">NOT RENDERED</span>') ) : ('<span class="self">THIS</span>') ) ) + '</td>'); document.writeln('<td class="hasOwnProperty" >' + ( object.hasOwnProperty(property) ? "Local" : "Inherited" ) + '</td>'); if (typeof object[property] == 'function') { document.writeln ('<td class="function">' + object[property] + '</td>'); } else { document.writeln ('<td class="function"> </td>'); } } As long as renderfunction = false, the object is fine coming out of this function. However, if I change renderfunction to true, all my properties become undefined. Why isn't this working as I expect it to? How should I fix it? Thanks in advance, -Brian. I'm writing a program that involves a network of interconnected nodes (or simply objects in my example below). It depends on being able to access properties of an object's linked objects (a bit oddly worded, sorry)... Problem is I'm not sure how to properly access those properties... see below please. <script> //This is an example of a problem im having in my own code... //I want to access the name of the object within the links array wintin the object... var objA = {name: "Object A", links: [objB, objC]}; var objB = {name: "Object B", links: [objC, objD, objE]}; var objC = {name: "Object C", links: [objB]}; var objD = {name: "Object D", links: [objE]}; var objE = {name: "Object E", links: [objD]}; //ex: I want to access the name of Object A's first link... console.log(objA.links[0].name); </script> I'm hoping to get "Object B"... But instead I get: TypeError: Result of expression 'objA.links[0]' [undefined] is not an object. Is there another way around this? Any thoughts are appreciated. Hello, I have a multi-dimensional object, derived from JSON returned by the Foursquare API. The object has the following structure (as printed using a print_r type method from http://www.openjs.com/scripts/others...hp_print_r.php PHP Code: '0' 'id' => "27110xxx" 'created' => "Sun, 11 Apr 10 15:09:45 +0000" 'timezone' => "America/New_York" 'user' ... 'id' => "48xxx" 'firstname' => "Barry" 'lastname' => "xxx" 'photo' => "http://playfoursquare.s3.amazonaws.com/userpix_thumbs/4abb5bxxxxxx.jpg" 'gender' => "male" 'display' => "xxxx. @ [off the grid]" '1' ... 'id' => "2538xxxx" 'created' => "Wed, 07 Apr 10 13:24:41 +0000" 'timezone' => "Europe/London" Could anyone tell me the best way to access its elements? I have this so far which gets the required values, but I want to preserve the order ie. get the data from the first element in the object first, then move to the next - each element represents a user so I want to keep their data separate. PHP Code: /* This is a custom function which has the same function as print_r */ function dump(arr,level) { var firstName, lastname, geolat, geolong, photo; var dumped_text = ""; if(!level) level = 0; //The padding given at the beginning of the line. var level_padding = " "; for(var j = 0; j < level + 1; j++) level_padding += " "; if(typeof(arr) == 'object') { //Array/Hashes/Objects for(var item in arr) { var value = arr[item]; if(typeof(value) == 'object') { //If it is an array, dumped_text += level_padding + "'" + item + "'\n"; dumped_text += dump(value,level + 1); } else { dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n"; } if (item == 'firstname') { firstname = value; document.write("First name: " + firstname + "<br />"); document.write(item); } if (item == 'lastname') { lastname = value; document.write("Last name: " + lastname + "<br />"); document.write(item); } if (item == 'geolat') { geolat = value; document.write("Latitude: " + geolat + "<br />"); document.write(item); } if (item == 'geolong') { geolong = value; document.write("Longitude: " + geolong + "<br />"); document.write(item); } } } else { //Stings/Chars/Numbers etc. dumped_text = "===>"+arr+"<===("+typeof(arr)+")"; } return dumped_text; } var myObj = <?php echo json_encode($checkin); ?>; alert(dump(myObj)); Sorry for the bloated code, I normally work in Java and PHP so although I understand the theory, I haven't worked with objects much in JavaScript before. Any help would be much appreciated! I'm not sure I phrased the question properly and it's probably easiest to show what I'm trying to get. Basically, I want to find all the properties(?) available for a single track object in iTunes. For example, this is how I access what's stored as the Album and Artist for a track: Code: var myTracks = myPlaylists(1).Tracks; alert(myTracks(1).Album); alert(myTracks(1).Artist); There are a ton of properties (like Album and Artist), but I don't know what they all are, so I was trying to list them like this, but it doesn't work: Code: for(var key in myTracks(1)) alert(key); It's probably obvious why this doesn't work, but does anyone know how to get this list? Thanks for any help! Do many programmers remember most of the object properties and methods or do they use IDE or references to find those specific objects. I'm starting to learn Javascript and seeing all the different type of objects available can be depressing. I have something like this var oneTest = new CustomObj({ prop1 : 'value1', prop2 : 'value2', prop3 : 'value3' }) var twoText = Object.clone(oneTest) twoText.prop2 = "newvalue2" And when I console log twoText I see something like +Data prop2 Inside Data is a prop2 that has the value of "value2". THAT is the one I want to change/override... yet the console shows me that the prop2 is outside of the data structure so when I am acting on the cloned obj I am not getting the results i need. I tried obj.extend etc.... and that didn't work, perhaps my syntax was wrong. Any advice? So I'm pretty much new to JS, and I'm trying to write something, and I'm having a problem. It's a color picker. So I have an object that defines the default color, and then when the color is updated, the different css classes need to be updated as well. So here's what I was trying to do Code: var colorPicker = { mainColor: "red", backgroundColor: this.mainColor + "bkgd", } So problem 1 is I keep getting "undefined" returned for "this.mainColor". If I use colorPicker.mainColor, it hasn't been created yet so it throws an error. Problem two is if I update mainColor from another function, say to make mainColor = "green", then backgroundColor doesn't automatically update. Any help is appreciated. Thanks Hey everyone, I'm a newbie writing a tic tac toe program using OOP. It was simple setting it up so that a player could click on a box to put an X or an O there, but I've run into serious issues when trying to make it so a player couldn't overwrite the AI's choice and the AI couldn't overwrite the player's. An example of this would be if I made the top right box an X and the AI then made the center box an O, and then I accidentally clicked the center box and made it into an X. I want to prevent that. Every box on the grid is an object with the property of "taken" that helps the program know if a box is empty or not, so as to avert any overwriting in the first place. If the box is empty, this.taken = 0. If the box is filled by a player, taken = 1. If filled by AI, taken = 2. I made it matter whether it was AI or human so later i can check if one of them got tic tac toe. Anyway, by default the constructor class sets this.taken = 0. But the method for checking availability and writing the X or O uses a switch which checks if taken = 0. If it is, it sets taken to either 1 or 2 and writes the necessary symbol. If taken = 1 or 2, it just alerts the player that the spot is taken. But for some reason the switch statement can't tell when taken = anything other than 0. It always executes the code for 0 even though the code for 0 inherently makes it so that taken never equals 0 again, which means case 0 cannot happen anymore. Below is the code with notes. Code: function main(input){//start of main function// function Click(who, where, what){ //this is the method for checking if it's taken or not and writing the X or O if it isn't// /*the argument who represents a number. 0 is no one, 1 is human, 2 is AI; where is a string literal representing the spot on the grid*/ switch(this.taken){ case 0: this.taken = who; document.getElementById(where).innerHTML = what; break; case 1: alert("this spot is taken"); break; case 2: alert("this spot is taken"); }//end switch }//end Click function Box(inputhere){//start of class// this.taken = 0; this.pick = Click; } //end of Box class// //object declarations (I cut out most of them and left only the relevant ones// var topleft = new Box(); var topmid = new Box(); var topright = new Box(); var centerright = new Box(); //end of object declarations// switch (input){ /*in each .pick(), the first arg is whether or not a player chose it (1 = player did, 2 = comp did). The second arg is which box and the third is whether to put an X or O. The input variable in the switch statement is an argument passed through main() when the player clicks on a box. Topleft passes 1.1, topmid passes 1.2 and so on.*/ case 1.1:{ //The first instance of .pick() in each case is what the player did. The second is what the AI will do in repsonse.// topleft.pick(1, "topleft", "X"); topmid.pick(2, "topmid", "<span>O</span>"); break; }//end of case 1.1 case 1.3:{ topright.pick(1, "topright", "X"); centerright.pick(2, "centerright", "<span>O</span>"); break; }//end of case 1.3 }//end of switch }//end of main// Is there anyone who has any idea why on earth this is happening? I've been at it for an embarrassing amount of hours. Also, thanks to anyone who even considers helping : ) (feel free to flame me if my code sucks or my post is too long or anything). hy all, I am creating an accordion menu that when i press the " UNIT " tab, it opens up a list of " Chapters " tab, and when i press on any one of those chapters, a list of lessons opens up. Till now, i have managed to create all the appropriate lists, but in default, lessons and chapters are opened automatically, and the lessons elements when pressed do not scroll back up to the chapters parents. My html5 file: Code: <script type="text/javascript" src="jqueryjs.js"></script> <script type="text/javascript" src="jqueryuiaccor.js"></script> <script type="text/javascript"> $(document).ready(function() { $('#accordion').accordion(); }); </script> <div id="container"> <div id="content"> <div id="sidebar"> <ul id="accordion"> <li> <a href="#recent" class="heading">Unit 1</a> <ul id="accordion"> <li> <a href="#recent" class="heading">Chapter 1 </a> </li> <ul id="accordion2"> <li> Lesson 1 </li> </ul> </ul> </li> <li> <a href="#recent" class="heading">Unit 2</a> <ul id="accordion"> <li> <a href="#recent" class="heading">Chapter 1 </a> </li> <ul id="accordion"> <li> <a href="#recent" class="heading" role="tab" aria-expanded="true">Chapter 2 </a> <ul id="accordion"> <li> <a href="#recent" class="heading">Lesson 1 </a></li> </ul> </li> </ul> </ul> </li> </ul> </div> </div> </div> My acorjs.js file: Code: $(document).ready(function() { $('ul#accordion a.heading').click(function() { $(this).css('outline','none'); if($(this).parent().hasClass('current')) { $(this).siblings('ul').slideUp('slow',function() { $(this).parent().removeClass('current'); $.scrollTo('#accordion',1000); }); } else { $('ul#accordion li.current ul').slideUp('slow',function() { $(this).parent().removeClass('current'); }); $(this).siblings('ul').slideToggle('slow',function() { $(this).parent().toggleClass('current'); }); $.scrollTo('#accordion',1000); } return false; }); }); Please HELP! Hi Experts here, Pls help. I have written the html code like this: <a href="http://mypage.com/docfiles" target="_blank"> Click </a> But the problem is when ever the user click the click option complete url is displaying in two ways 1)on the buttom of the status bar 2)Right click on the option open the properties than also we are getting the complete url. But we don't want to see the complete url,How to hide the Url. Please give me solution I am struggling alot. Thanks and Regards, Srinivas yadav. Hi all! I'm pretty new to JavaScript and completely new to this forum. I'm James. Well uh, I'm not sure how to... I wanted to make something like this using javascript... Code: myObject.someMethod('something').anotherProperty much like the Code: document.getElementById('someId').style.morestuff But the thing is, I've been around every DOM whatnot I can find, I just can't seem to make it work. I kinda need it to make my own DOM for some API i'm writing. So I can write like... Code: function someGreatAPI(){ this.property1=''; this.property2=''; //... this.method1 = function(var1){ //this should make my firstMethod this.nestedProperty = 0; this.nestedMethod = someFunction; //firstMethods nested method } } //so I can use it like... var obj = new someGreatAPI(); obj.method1(10).nestedMethod(); It has to be possible, it's possible with document.getelementbyid, right? it has to be. Thanks in advance. i m trying to extract data from an xml file and display data on Google maps but when i try to run my code In IE - Access denied error is display (while accessing the xml file) Mozilla - code is working fine but displays following error - Error: xmlDoc.getElementsByTagName("lat")[1] is undefined Source File: file:///I:/BE%20Project%20Data/coding/Myexample/exam2.html Line: 48 HTML file- <html> <head> <title>Google Maps JavaScript API v3 Example: Fusion Tables Layer</title> <link href="http://code.google.com/apis/maps/documentation/javascript/examples/default.css" rel="stylesheet" type="text/css" /> <style type="text/css"> html { height: 100% } body { height: 100%; margin: 0px; padding: 0px } #map_canvas { height: 500px;width: 800px } </style> <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script> <script type="text/javascript"> function initialize() { if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } else {// code for IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.open("GET","agridata.xml",false); xmlhttp.send(); xmlDoc=xmlhttp.responseXML; var latlng = new google.maps.LatLng(48.75028,-94.91667); var mapOpts = { zoom: 5, center: latlng, mapTypeId: google.maps.MapTypeId.ROADMAP, }; var map = new google.maps.Map(document.getElementById("map_canvas"),mapOpts); var l1=xmlDoc.getElementsByTagName("lat")[1].childNodes[0].nodeValue; var l2=xmlDoc.getElementsByTagName("lng")[1].childNodes[0].nodeValue; var pt = new google.maps.LatLng(parseFloat(l1), parseFloat(l2)); var marker = new google.maps.Marker({ position: pt, map: map, title: 'Just a simple marker'}); } </script> </head> <body onload="initialize();"> <h1>output</h1> <div id="map_canvas"></div> </body> </html> XML file - <?xml version="1.0"?> <markers> <marker> <lat>52.09667</lat> <lng>-173.50056</lng> <state>Alaska</state> <county>Aleutian</county> </marker> <marker> <lat>48.75028</lat> <lng>-94.91667</lng> <state>Minnesota</state> <county>Lake of woods</county> </marker> <marker> <lat>52.09667</lat> <lng>-173.50056</lng> <state>Washington</state> <county>Stevans</county> </marker> </markers> do let me know the reason behind the undefined error and ACCESS DENIED error ... i have tried modification in the security setting of the browser but error is not solved yet ... thks Hi all, I have multiple forms on one page with the same element name and one of them is the <span>. Below is my sample code for a simple html file for testing purposes. I have no problem accessing the <input> element, but i had problems with the <span> element. Anyone knows why? In this scenario, i won't be able to use the document.getElementById() as both <span> have the same name. Code: <html> <head> Test <SCRIPT LANGUAGE="JavaScript"> // JavaScript statements go here function test(tmpForm) { window.alert(tmpFrm.elements["weight"].value); window.alert(tmpForm.elements["error"].innerHTML); } </SCRIPT> </head> <body> <form id="form_137" name="form_137"> <input id="weight" name="weight" value="" /> <span id="error" name="error">abc</span> <INPUT TYPE="button" id="btnSubmit" NAME="btnSubmit" VALUE="Submit" onClick="test(this.form);"> </form> <form id="form_137_down" name="form_137_down"> <input id="weight" name="weight" value="" /> <span id="error" name="error">zzz</span> <INPUT TYPE="button" id="btnSubmit" NAME="btnSubmit" VALUE="Submit" onClick="test(this.form);"> </form> </body> </html> OK, There's a script on my site that's included like <script src='somePHPfile.php?params... etc It generates an image with some text in it and a few links. When I click 'view source' it just comes up with the <script> tags and nothing else. In Firefox, if I right click on the actual image and go to this frame > view source, I can see everything it's doing. Is there some way I can access this code with Javascript/jquery? I've tried html/dom parsers, etc. with no luck. I have an html file I've built with embedded Javascript (using ActiveX) that successfully reads a file on my local hard drive when I run the html file through my web browser (IE) locally. However, when I copy the html page up to a webserver and access it through the internet, it doesn't appear to be reading the local file. I'm assuming this can't be done because of security reasons? Am I correct in that? Is there any way using Javascript/ActiveX that you can get a webpage on the internet to access a file on the visitor's local drive? (other than cookies)
I HAVE BEEN TRYING TO FIGURE OUT THE PARAMETERS IN THE FUNCTIONS, INCLUDING THE ARRAYS [i], [p], ["get_" + i], ["set_" + i] AND HOW THE METHODS ARE BEING CALLED IN RELATION TO i, p and val, so that I can make sense of this code. If possible can you explain the code also What I will like to know are the properties and methods of the objects generated in the following code? Also I want to know how I can use those methods to show and change the name and age for the emp2 object. this is the code: function Employee(properties) { for (var i in properties) { if (properties.hasOwnProperty(i) && typeof properties[i] != 'function') { this["get_"+i] = (function(p) { return function() { return properties[p]; }; })(i); this["set_"+i] = (function(p) { return function(val) { properties[p] = val; }; })(i); } } } var emp1 = new Employee({ name: "Bob", age: 35, foo: function() {} }); var emp2 = new Employee({ name: "Gary", age: 54 }); How can i display a javascript object having [CODE]var myVarr = [{"name":"xyz","age":21}, {"name":"cde","age":25}].[CODE] in a table in jsp page? Regards, Anas I am rather new to javascript programming and not sure if this is the best approach to handle a problem. In setting up a simple image display that can later be modified to a rotator, I am using the following code window.document.display1.src = image1.src; now the question is when modifying that to be more dynamic, where display1,display2,.. can refer to a different image (or set). var Image = "image"; var Display = "display"; for (i=1; i<n; i++){ window.document.this[Display+i].src = this[Image+i].src; } I know the right hand side of the equation is working (alert() displays the right soure), but the problem is the left hand side. I guess because of me not fully understanding the way objects work. why this[] works on the right and not on the left? and how do I resolve it? All your comments, and a push in right direction are appreciated. I am doing my homework for my class, and I don't usually ask for this much help because I get most of them done by myself. However, I am having a really hard time to understand this time. I have lots lots of questions...I tried to follow the instructions that I got from my professor, but it seems not clear enough to me... If anyone can fix or add on my codes, I will be really really appreciated....and here is the instructions and my codes.. If the form validates, instead of returning true, call the GetValues() function followed by the DisplayOutput() function. so, I changed result true to calling functions like this, Code: if (blnError == true){ return false; } else { DisplayOutput(); GetValues(); } In the .js file, create a PortraitOrder class using the following specifications Properties: portrait, copies, size, buyer Method: CalculateCost () -- determines the size (radio buttons) and then mutiplies the related cost by the number of copies Code: function PortraitOrder(){ var cost; this.copies = ""; this.portrait = ""; this.size = ""; this.buyer = ""; var CalculateCost = { met1 : function () { if(size == 0){ cost = this.copies * 10 } else if(size ==1){ cost = this.copies * 20 } else if(size ==2){ cost = this.copies * 10 } else if(size ==3){ cost = this.copies * 30 } else{ cost = this.copies * 20 } } } } Create a new instance of the class named portraits as a global variable in the ,js file -" I don't see why I need this. So I did not create Create a GetValues() function that will retrieve the values from the form fields (document.forms[0].element.value) and assign them the properties of the instance of the PortraitOrder class. use a for loop to retrieve the value from the radio buttons use the prototype property to add a new property named email to the instance of the class retrieve the value from the form field and assign it to the new email property Code: function GetValue(){ this.copies = document.forms[0].Copies.value; this.buyer = document.forms[0].Buyer.value; var file = document.getElementsByName('Filename'); for(var i = 0; i < file.length; i++){ if(file[i].checked){ this.portrait = file[i].value; } } var sizes = document.getElementsByName('Size'); for(var i = 0; i < sizes.length; i++){ if(sizes[i].checked){ this.size = sizes[i].value; } } GetValue.prototype.email = document.forms[0].Email.value; } Create a DisplayOutput() function that calls the CalculateCost () method for the current instance of the class. displays the image using the value from the portrait property which contains the filename. Be sure to include height and width (and that would be why all of the images had to be the same dimension. These values can be hardcoded. The filename, however, may NOT be hard coded.. it must use the object.property format. displays the buyer, email, copies, size, and cost using the object.property format (document.forms[0].element.value is not permitted) The cost must be formatted as ##.## where # represents a number (Hint: Use a method of the Number class). It is NOT okay just to concatenate .00 to then end of the cost. Code: function DisplayOutput(){ CalculateCost.met1(); document.write("buyer: " + this.buyer); document.write("Email: " + email); document.write("Portrait: " + this.portrait); document.write("Copies: " + this.copies); document.write("Cost: " + "$"+cost.toFixed(2)); document.write("Thank you"); } The order form must include the site's header and footer and coordinate with the rest of the site. There is no form processing file, everything is done in the .js file. You may think like, this is horrible codes. And yes, it is. I know probably this is totally odd. This is why I came here for ask help. Also, I spent days to tried, but I could not get any idea...Anyone please help me on this? |