JavaScript - Attempting To Understanding Privileged Methods And Object.create
This is in reference to Crockford's articles found he
http://javascript.crockford.com/prototypal.html http://javascript.crockford.com/private.html I'm attempting to understand the use of privileged methods when used with Object.create. I put together a quick demo (code below) that shows what happens when I use Object.create to create a new object based on one that has a privileged method. The outcome is not pleasant, as changing the value in the first object also changes it in the second. Unless I am reading Crockford's articles incorrectly, this makes Object.create almost useless for anything but objects that have only public members. I've seen many JavaScript programmers use closures extensively to create private members, and that still holds to be a good programming practice. However I still can't find an elegant way to create inheritance in combination with closures in JavaScript, given downfalls such as the one I mentioned above. With all of that said I still think Crockford has a nice way of programming, creating factory functions that produce objects, staying away from the prototype property and making the language look more functional. Here's the code to demonstrate what I'm referring to. Firebug needs to be enabled to view the console.debug output, otherwise convert them to alerts. Code: if (typeof Object.create !== 'function') { Object.create = function (o) { function F() {} F.prototype = o; return new F(); }; } var o = (function() { var msg = "hi"; return { msg: function(m) { if (m === undefined) { return msg; } msg = m; } }; })(); var foo = Object.create(o); var bar = Object.create(foo); console.debug(foo.msg()); // "hi" foo.msg("what?"); console.debug(foo.msg()); // "what?" console.debug(bar.msg()); // "what?" Similar TutorialsI still can't understand very well when to use and when NOT to use parenthesis when calling/using methods and functions. Case 1: Where I commented "// No parenthesis.", could someone explain why not. And at the end, where the commen reads "// Parenthesis. ? Code: /* This function will be used as a method inside the objects. */ function getPayment() { thePayment = 250; thePayment += (this.seats == 'leather') ? 100 : 50; thePayment += (this.engine == 'V-8') ? 150 : 75; thePayment += (this.radio == 'CD Player') ? 30 : 10; return thePayment; } /* Object Constructor (prototype of the object). */ function car(seats, engine, radio) { this.seats = seats; this.engine = engine; this.radio = radio; this.payments = getPayment; // No parenthesis. } /* Creates an instance called 'my_car' out of the 'car' object. */ var my_car = new car('cloth', 'V-6', 'Tape Deck'); /* Object Initializer - automatically instantiates the object. */ var carObj = { seats: 'leather', engine: 'V-8', radio: 'CD Player', payments: getPayment // No parenthesis. No comma after last item. } // Firebug... console.log(my_car.payments()); // Parenthesis. console.log(carObj.payments()); // Parenthesis. /* vim:set foldmethod=indent: */ Case 2: Please look at the comments. Code: window.onload = initAll; // Why no () here? function initAll() { window.doStuff(); // Why () here? } function doStuff() { var msg_text = 'I love you so much!'; var msg_link = window.document.getElementById('msg_link'); console.log(msg_link); var msg_box = window.document.getElementById('msg_box'); msg_link.onmouseover = function() { //msg_box.value = msg_text; msg_box.setAttribute('value', 'May the force be with you!'); }; msg_link.onmouseout = function() { /* This works in ie. */ //msg_box.value = ''; /* Doesn't work in ie7 (and probably not in ie6 either). * Perhaps the code above is reasonable. */ msg_box.removeAttribute('value'); } } /* vim:set foldmethod=indent: */ 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. 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. Hey all, I am having issues with below script. Firebug returns: form[0] is undefined [Break on this error] $(form[0].elements).each(function() { I have this under my form: <script> var thisForm = $('#validateForm'); thisForm.validation(); </script> Code: (function($) { /* Validation Singleton */ var Validation = function() { var rules = { email : { check: function(value) { if(value) return testPattern(value,".+@.+\..+"); return true; }, msg : "Enter a valid e-mail address." }, url : { check : function(value) { if(value) return testPattern(value,"https?://(.+\.)+.{2,4}(/.*)?"); return true; }, msg : "Enter a valid URL." }, required : { check: function(value) { if(value) return true; else return false; }, msg : "This field is required." } } var testPattern = function(value, pattern) { var regExp = new RegExp("^"+pattern+"$",""); return regExp.test(value); } return { addRule : function(name, rule) { rules[name] = rule; }, getRule : function(name) { return rules[name]; } } } /* Form factory */ var Form = function(form) { var fields = []; $(form[0].elements).each(function() { var field = $(this); if(field.attr('validation') !== undefined) { fields.push(new Field(field)); } }); this.fields = fields; } Form.prototype = { validate : function() { for(field in this.fields) { this.fields[field].validate(); } }, isValid : function() { for(field in this.fields) { if(!this.fields[field].valid) { this.fields[field].field.focus(); return false; } } return true; } } /* Field factory */ var Field = function(field) { this.field = field; this.valid = false; this.attach("change"); } Field.prototype = { attach : function(event) { var obj = this; if(event == "change") { obj.field.bind("change",function() { return obj.validate(); }); } if(event == "keyup") { obj.field.bind("keyup",function(e) { return obj.validate(); }); } }, validate : function() { var obj = this, field = obj.field, errorClass = "errorlist", errorlist = $(document.createElement("ul")).addClass(errorClass), types = field.attr("validation").split(" "), container = field.parent(), errors = []; field.next(".errorlist").remove(); for (var type in types) { var rule = $.Validation.getRule(types[type]); if(!rule.check(field.val())) { container.addClass("error"); errors.push(rule.msg); } } if(errors.length) { obj.field.unbind("keyup") obj.attach("keyup"); field.after(errorlist.empty()); for(error in errors) { errorlist.append("<li>"+ errors[error] +"</li>"); } obj.valid = false; } else { errorlist.remove(); container.removeClass("error"); obj.valid = true; } } } /* Validation extends jQuery prototype */ $.extend($.fn, { validation : function() { var validator = new Form($(this)); $.data($(this)[0], 'validator', validator); $(this).bind("submit", function(e) { validator.validate(); if(!validator.isValid()) { e.preventDefault(); } }); }, validate : function() { var validator = $.data($(this)[0], 'validator'); validator.validate(); return validator.isValid(); } }); $.Validation = new Validation(); })(jQuery); Hi, every time I try and alert: [ { number:0, secondnumber:0 }, { number:2, secondnumber:1 }, { number:1, secondnumber:2 } ] it just shows [object object], [object object], [object object]. Why is this and what can I do to make the record be shown as it is above in an alert? Thanks. I have a select with a OnChange Function. I would like to know how to create a different object depending on the selection on the Select. Example: MySelect have Option 1 and Option 2, so If (Myselect.value == Option 1) {Create Object 1} If (Myselect.value == Option 2) {Create Object 2} I'm using the object under <body> and it's working, but when I'm trying to use it under a <script> does not work. This is the object I'm trying to create: (It is a map) so what I'm trying is to change the values or map depending on the selection of the Select. <object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,0,0" width="900" height="600" id="zoom_map" align="top"> <param name="movie" value="us_albers.swf?data_file=senate.xml" /> <param name="quality" value="high" /> <param name="bgcolor" value="#FFFFFF" /> <embed src="us_albers.swf?data_file=senate.xml" quality="high" bgcolor="#FFFFFF" width="100" height="100" name="Clickable U.S. Map" align="top" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer"> </embed> </object> Thank you very much I'm writing a script in javascript(actually a chrome extension) and I need an object that I can write to it like this(sorry, don't know how to explain it better) and then I convert it to string with format of json. Code: id[129].weekDay[6].hour[23] = 0 Here, id is an array, that each element in it contain another array(weeksDay) and in that array each contain another array(hour). The id indices are unlimited, for weekDay 7 and hour 24. I searched in google but i couldn't find what I wanted. Actually don't know the best keyword to search.(objects in arrays?) I don't know what exactly it is called, I can write it's declaration in VB.NET if that helps you. I know I can use the functions like parseFromString() to access and modify an existing XML documents, but is it possible to use JavaScript to create a blank xml document? I want to take data entered into the client, package it up as XML and use ajax to transmit it to the server. So far I've written my own class to create a simple xml document, but I'd like to do it properly with the inbuilt functions. this is my first time attempting this operation. I want to take some javascript out of my html. here is the original: Code: <!--div#9begin--><div style="float: left; height: 166px; width: 1px;"> <img alt="" src="images/border_short_vert.png" height="169" width="1" /> </div><!--div#9end--> <!--div#10begin--><div style="width: 225px; height: 155px; float: left; height: 16px; background-color: #000000; color: #FFFFFF; margin-left: 0px; margin-bottom: 0px; font-size: small; padding-left: 0px;"> <img alt="" src="images/news.png" height="16" width="222" /><!--div#11begin--><div style="width: 225px; height: 155px; float: left;"></div><!--div#11end--> <script type="text/javascript">// <![CDATA[if(document.layers){document.write('<ilayer id="ns4div" width="'+swidth+'" height="'+sheight+'" bgcolor='+sbcolor+'><div id="ns4div1" width="'+swidth+'" height="'+sheight+'" onmouseover="sspeed=0;" onmouseout="sspeed=rspeed"></div></ilayer>')} if(document.getElementById||document.all){document.write('<div style="position:relative;overflow:hidden;width:'+swidth+'px;height:'+sheight+'px;clip:rect(0 '+swidth+'px '+sheight+'px 0);background-color:'+sbcolor+';" onmouseover="sspeed=0" onmouseout="sspeed=rspeed"><div id="iens6div" style="position:relative;width:'+swidth+'px;"></div></div>');} // ]]> </script> </div><!--div#10end--> and here's my attempt: Code: <div style="width: 225px; height: 155px; float: left; height: 16px; background-color: #000000; color: #FFFFFF; margin-left: 0px; margin-bottom: 0px; font-size: small; padding-left: 0px;"> <img alt="" src="images/news.png" height="16" width="222" /><script type="text/javascript" src="docwrite.js"></script> <div style="width: 225px; height: 155px; float: left;"></div> </div> along with my js: Code: if(document.layers) {document.write('<ilayer id="ns4div" width="'+swidth+'" height="'+sheight+'" bgcolor='+sbcolor+'><div id="ns4div1" width="'+swidth+'" height="'+sheight+'" onmouseover="sspeed=0;" onmouseout="sspeed=rspeed"></div></ilayer>')} if(document.getElementById||document.all) {document.write('<div style="position:relative;overflow:hidden;width:'+swidth+'px;height:'+sheight+'px;clip:rect(0 '+swidth+'px '+sheight+'px 0);background-color:'+sbcolor+';" onmouseover="sspeed=0" onmouseout="sspeed=rspeed"> <div id="iens6div" style="position:relative;width:'+swidth+'px;"></div></div>');} what is the problem? Have I not performed the extraction properly? Hi All! Thanks in advance to any and all who help me. What we are trying to do is have a form where customers can use a conditional logic based form that upon submission will redirect to checkout with an appropriate product bundle being populated in the shopping cart. I have some experience with creating forms, in fact I have made a decent form that I have modified from an online form builder... the problem is I have no idea how to auto-fill the shopping cart... period. From what I have read in my research this should be a function of Javascript. I have a decent working knowledge of php, and html, but I am pretty clueless when it comes to Javascript, if anyone could point me in the right direction for this project I would really appreciate it. I can't get any info from Firebug except that one line, uncaught exception [object Object]. The code fully worked, then I needed to make it dynamically create Sortables from the scriptaculous library based on how many X were in a table in my database, which I've done, and I'm thinking it may be a simple slight parse error of some type, I'm not too good with Javascript, because now my script barely works. I've double checked the script's source code, the PHP variables are exactly what they should be. Code: print<<<HERE Sortable.create('sortlist$box', { tag: 'img', overlap:'horizontal',constraint:false, containment: $list, dropOnEmpty: true, onChange: function(item) { var list = Sortable.options(item).element; if(changeEffect) changeEffect.cancel(); changeEffect = new Effect.Highlight('changeNotification', {restoreColor:"transparent" }); }, onDrop: function(item) { var thing=Sortable.options(item).element.identify(); var anchors = document.getElementById(thing).childNodes.length-2; if(anchors > 20){ alert('This box had 20 creatures in it already, your last action has not been saved.'); window.location.reload(); } else{ new Ajax.Request("saveImageOrder.php", { method: "post", parameters: { data: Sortable.serialize("sortlist$box") } }); } } }); HERE; $box++; } ?> }); </script> if you solve this I'll send ya $10 via paypal My question is about the following javascript function that converts 15 digit salesforce IDs to 18 digit salesforce IDs. The function was originally posted here. Developer 1 wrote the function: function convertToCaseInsensitiveId(id) { var hash = ''; for (var c = 0; c < 3; c++) { var h = 0; for (var i = 0; i < 5; i++) { var ch = id.charCodeAt(i + c * 5); if (ch >= 65 && ch <= 91) h += Math.pow(2, i); } hash += String.fromCharCode(h > 26 ? h + 48 - 26 : h + 65); } return id + hash; } Developer 2 said: Since the checksum numbers are mapped to AB..YZ012345, 25 gives Z. The following line > hash += String.fromCharCode(h > 26 ? h + 48 - 26 : h + 65); should be > hash += String.fromCharCode(h > 25 ? h + 48 - 26 : h + 65); otherwise 26 would be mapped to opening bracket (ASCII # 91). Which developer's solution is correct? Hi, can anyone tell me... Code: function Obj() { this.recursiveMethod=function () { //...how to invoke Obj.recursiveMethod from here? } } Gus I am building a website and I need to gather some information but I feel that prompts are unappealing. Maybe something like a form but it defines whatever is typed in as a variable?
I have a javascript assignment I am having difficulties with. I have most of it complete but need some assistant with the last portion and that is to get my display function to work. I am sure that this is something I should know how to do but for the life of me can't seem to figure out and just need a little guidance. Code: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html lang="en" xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"> <head> <title>Lab03</title> <h1> Person Information </h1> <script type= "text/javascript" charset= "utf-8"> function Person( ) { this.lastname = ' '; this.firstname= ' '; this.areacode= ' '; this.phone_number= ' '; this.show_person = ' '; } </script> <script type= "text/javascript" charset= "utf-8"> var per1 = new Person function getInput( ) { lastname= prompt("please enter your last name: "); firstname= prompt("please enter your first name: "); areacode= prompt("please enter your area code: "); phone_number= prompt ("Please enter your phone number (ex:888-8888): "); return per1; } per1= getInput( ); </script> </head> <body> <script type ="text/javascript" charset= "utf-8"> function show_person( ){ if( firstname == "" && lastname == "" ) { document.writeln( "Name: Unknown" + "<br/>" ); } else if( firstname == 'null' && lastname == 'null' ) { document.writeln( "Name: Unknown" + "<br/>" ); } else if ( firstname == "" || lastname == "") { document.writeln("Name: " + lastname); document.writeln(firstname + "<br/>"); } else if ( firstname == 'null' || lastname == 'null') { document.writeln("Name: " + lastname); document.writeln(firstname + "<br/>"); } else { document.writeln("Name: " + lastname + ", "); document.writeln(firstname + "<br/>"); } else if ( areacode == "" || phone_number == "" ) { document.writeln ("Phone: "); } else if ( areacode == 'null' || phone_number == 'null' ) { document.writeln ("Phone: "); } else { document.writeln('Phone: (' + areacode + ')'); document.writeln(phone_number); } return this.show; } </script> <noscript> <p>You must enable javascript to view all the features of this page.</p> </noscript> </body> </html> Can someone help me out and tell me what it is I need to do to make it work? I actually had it working when I was able to put all the code in the get function but was told I needed a separate display function so any input is greatly appreciated. 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. Hi all, I'm stumped on finding a way in javascript to create an object factory whose instances are also object factories. In short I want something like that below, but no joy ... any clues? Code: function createClass () { return new createClass() function createClass() { return new createInstance () function createInstance () { //Default properties, values and methods which might later be extended } } } var createDoor = createClass(); var door1 = createDoor(); var door2 = createDoor(); var createChair = createClass(); var chair1 = createChair (); var chair2 = createChair (); Ignore post (if mod, please delete)
Hello together! I generate html code with jsp. In that jsp there a several framesets and frames. And yes i know, frames are not really up to date but it's an old program and i have to deal with it now. Anyway, in the top frameset i have an onload attribute like onload="load()". In the function load i want to access the Element.prototype object. But unfortunately typeof Element gives me "undefined". So i looked a little deeper and found that window.toString() gives me "[object]" and not as expected "[object window]" so somehow my window doesn't know that its construcor is Window. window.construcor is "undefined" as well. And i don't have access to the Element object. I really don't know where the error could be. When the page is loaded and i access the same window over the console, then everything is right. But in my function a can't get access to the objects i need. I also don't know what part of the code could be useful to post here, but maybe someone had a similar problem before? i should say that this problem only occurs in IE8. In IE9 it works perfectly. Has anyone any idea?? Hi everybody! I've a problem and I'm not able to solve it alone. I want to invoke java methods of a self written java programm with javascript. I found something like a tutorial (http://stanislavvitvitskiy.blogspot....lications.html), but it has not worked. I put my class file in a jar file and when I want to load it in javascript i get an error. I tried it this way: var url = new java.net.URL('C:/java_js' + '/xultest.jar'); var cl = new java.net.URLClassLoader(url); var aClass = java.lang.Class.forName("com.stan.XULDemo", true, cl); var inst = aClass.newInstance(); // Calling 'sum' function from java var a = inst.sum(2, 3); alert(a); // Will alert '5' Can anyone please help, and say to me what's wrong about it? Or does anyone have another aproach to call java methods with javascript? cheers, Martin |