JavaScript - Inheritance In Module Pattern
Hi, I would like to know which is the best approach when trying inheritance with js - module pattern. In the example below, I want that parent.hi() be fired from child:
Code: var parent = function(){ return{ hi: function(){ console.info('hi'); } } }(); var child = function(){ return{ bye: function(){ console.info('bye'); }, hi: function(){//look he parent.hi(); } } }(); child.hi(); Is there a better way to do this ? Thanks in advance Similar TutorialsWhat are the benefits of prototypal inheritance over classical inheritance?
What are the benefits of prototypal inheritance over classical inheritance?
Hi, I have this search module at the top and bottom of my web page Here is the mark-up for the same HEADER SEARCH MODULE Code: <div id="searches"> <ul id="topTabSet"> <li class="current" id="web-top"><a href="javascript:;">Web</a></li> <li id="blog-top"><a href="javascript:;">Blog</a></li> <li id="image-top"><a href="javascript:;">Images</a></li> <li id="video-top"><a href="javascript:;">Video</a></li> <li id="product-top"><a href="javascript:;">Products</a></li> </ul> <form name="topSearchForm" id="topSearchForm" method="GET"> <fieldset> <label for="web-search">Enter search terms</label> <input style="display: none;" name="invocationType" value="" type="hidden" /> <input name="query" id="webSearch-top" type="text" /> <input id="submit" name="tSearchSubmit" class="submit" value="" alt="Search" type="submit" /> </fieldset> </form> </div> FOOTER SEARCH MODULE Code: <div id="searchesFt"> <ul id="bottomTabSet"> <li class="current" id="web-bottom"><a href="javascript:;">Web</a></li> <li id="blog-bottom"><a href="javascript:;">Blog</a></li> <li id="image-bottom"><a href="javascript:;">Images</a></li> <li id="video-bottom"><a href="javascript:;">Video</a></li> <li id="product-bottom"><a href="javascript:;">Products</a></li> </ul> <form id="bottomSearchForm" name="bottomSearchForm" method="GET"> <fieldset> <label for="web-search">Enter search terms</label> <input style="display: none;" name="invocationType" value="" type="hidden" /> <input name="query" id="webSearch-bottom" type="text" /> <input id="submit" name="bSearchSubmit" class="submit" value="" alt="Search" type="submit" /> </fieldset> </form> </div> I had written written a JS which is all junk. I could manage to get tab stay selected when i click on it. I am not even in a position to post it here Here is what I am looking for: 1) all the tabs open the search in a new window/tab on submit/click except for the "Blog" tab which opens the search within the same page 2) The search should be directed to different URLs based on the tab selection. i.e. web = http://www.testexample.com/web/?q="Entered search term"&invocationType="testinv" blog = /search/?q="Entered search term"&invocationType="testinv" images = http://www.testimages.com/image/?q="Entered search term"&invocationType="testinv" video = http://www.testvideos.com/video/?q="Entered search term"&invocationType="testinv" products = http://www.testproducts.com/product/?q="Entered search term"&invocationType="testinv" 3) an the above is for the header search and footer search modules. Could someone please please help me with some code to achieve this. I know I am asking for too much. But I am helpless. please help me. Thanks Hi, Im using a authoring tool to develop an elearning test course. The course is composed of several HTML pages with Buttons for the multiple choice test. The setup of the course is that it will only ask 10 questions out of a pool of 30 questions. When the HTML & JS files are online, the test takes 20-40seconds to load. I believe it is related to the code that selects the 10 questions from the 30. I've singled out the code that does the select random pages... Is there any way to optimize the code? I've attached the HTML (in txt format) page where the javascript can be found. Looking forward to your replies! Hi All, Following pattern in bold is present in a variable bigvar which has around 100 characters. Variable test may vary var test = CONFIG_ID CONFIG_ID="_N/D1/N1/S4/P1/E1%231.1.1/T 3" Here is what I have tried: var RE = new RegExp (test+"=[A-Za-z0-9_%\"\.\/]+\s{2}[0-9]+"); var matched_val = bigvar.match(RE); alert(matched_val); It is giving null as match. Can anyone help me on this ? Thanks, Vinay HI I have seen this pattern in http://www.altsoftware.com/index.php . there are news menu in the left side . Please visit this site . The news will be change with a really beautiful pattern in every 5 seconds I think it has been written with jquery but I don't know how can I make something like this How can I do so ? thanks I have the code for the page below that has form with a text box for a email address. I am doing this exercise trying to understand the concepts of pattern matching in a function. ***My expression on needs to tests for *** 1. One or more word characters= /\w+ 2. one period= \.\ 3. one hyphen sign= \-\ 4. two or more characters that a-z, A-Z, 0-9, period or hyphen= \W+\. I have a alert message that display when the user has returned a invalid address. I don't need regex for testing an entire email address that is out of the scope that I am studying. I have wrote a function but to honest I am not sure where I have gone wrong and not exactly where I need to go to execute it correctly. <!DOCTYPE html> <html> <head> <title>Lab 2 Part 3</title> <meta charset="UTF-8" /> <body> <script> function validation(address) { var ok= address.search(/\w+\.\-\@\W+); if (ok==0) return true; else alert("please enter a valid email address"!!) return false; } </script> <form action="http://yahoo.com/formtest.php" method="post" onsubmit="return validation();"> <p> <label> Email Address: <input type="text" name="address" size="30"/> </label> </p> <input type="submit" value="Submit" /> </form> </body> </html> Hello All, can someone pls help me with the error shown in firebug for the code below: Firebug error: Object.method is not a function Object.method('superior', function (name) { Constructor functions work until it gets to /* Super method template */. Thats where the error comes from. Code is from javascript - good parts. var mammal = function(spec) { var that = {}; that.get_name = function() { return spec.name; } that.says = function() { return spec.saying || ''; } return that; } var myMammal = mammal({name: 'Herbie', saying: 'Im herb the mammal'}); console.log(myMammal.get_name()); console.log(myMammal.says()); var cat = function(spec) { spec.saying = spec.saying || 'Meow!' var that = mammal(spec); that.purr = function(n) { var i, s = ''; for(i=0; i < n; i +=1) { if(s) { s += '-'; } s += 'r' } return s; } that.get_name =function() { return that.says() +' '+ spec.name +' '+ that.says(); } return that; } var myCat = cat({name: 'Henrietta!', saying: 'Im a pussycat'}) console.log(myCat.get_name()); console.log(myCat.purr(3)); /* Super method template */ Object.method('superior', function (name) { var that = this, method = that[name]; return function ( ) { return method.apply(that, arguments); }; }); /* Super method e.g. */ var coolcat = function (spec) { var that = cat(spec), super_get_name = that.superior('get_name'); that.get_name = function (n) { return 'like ' + super_get_name( ) + ' baby'; }; return that; }; var myCoolCat = coolcat({name: 'Bix'}); console.log(myCoolCat); var name = myCoolCat.get_name(); console.log(name); I'm trying my best to figure this out with google, but I've found 4 different syntaxes and can't get any of them to work. I need to have several classes extend another for my chess game. I need classes, Rook, Knight, Bishop etc... all extend from class Piece. can anyone help me with the syntax var Piece = Class.create(); Piece.prototype = { initialize: function(src, square){ //init stuff here }, setSqua function(square){ //sets the square of the piece }, } Rook.prototype = new Piece(); function Rook(src, square) { Piece.apply(src, square); } Thanks to anyone who helps I am new to javascript and would like to search for the element with id but the element id are changing if i use different navigation in that web page example: C21_W68_V69_notes_struct.text changes to C24_W78_V79_notes_struct.text or any other name next time hence i would like to search that element using a pattern like notes_struct.text as there exist only one element ending with this pattern. I am using old version IE and would like to use javascript only. Kindly help. Hi, I want to validate the value in a textbox such that the first character should be a symbol like # or $ followed by 2 alphabets which is followed by numbers.I tried a pattern like if(/(#{1}|${1})\D{2}\d{6}/.test(str.value)) But this is not working. Can someone help me the correct pattern? I am trying to do a pattern match and check something in a condition but cant get it to work. The first value changes and I need to check and do something if I get a hit on it. Code: var mydata = "?first=one&second=two&third=three"; if (mydata.indexOf("first") == "something") { alert("No Hit"); } else { alert("Hit"); } Basically I am trying to find out if first is equal to one in the mydata string. Please advise because my above attempt is not working. 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 I'm having a javascript problem with nested elements. Consider an example in which you have two nested elements with element 2 being inside of element 1 and only element 1 has an onmouseout event handler. <div style="position:relative;border:1px solid red;width:300px;height:300px" onmouseout="alert('whatever')"> //element 1 <div style="position:absolute;border:1px solid blue;left:50%;top:50%;margin-left:-50px;margin-top:-50px;width:100px;height:100px">//element 2 </div> </div> The 2 problems here are as follows: 1- Moving the mouse pointer over element 2 from element 1 causes a onmouseout with element 1. But this is a minor problem. 2- Moving the mouse pointer from element 2 back to element 1 causes a mouseout with ,I believe, element 2 even though there is no onmouseout event handler here. This is a major problem. Is problem #2 due to possibly an automatic inheritance of the onmouseover handler from element 1 onto element 2 OR is it the result of event capturing or what else? I can't tell either way. If it's due to inheritance how do you stop this from taking place? The strange thing is that tutorials give this kind of scenario with element 2 inside of element 1 with both elements having the same event handler but they don't say what happens in this case with just one element having a specific event handler. Thank you. Hi! This is probably a classic inheritance thing... I have two objects, C1 and C2. Both contains a callback method named 'callback'. Now, if I let C2 inherit from C1, then C1's 'callback' gets overridden by C2's. The problem is I still want C1's methods to access their own 'callback' method. Is this possible, and is it "valid"? Am I headed down disaster lane here? Should I re-think and refactor? Example: Code: function C1 () {}; C1.prototype.callback = function () { console.log('c1 called'); }; C1.prototype.call = function () { //do stuff this.callback(); }; function C2 () {}; C2.prototype = new C1(); C2.prototype.callback = function () { console.log('c2 called'); }; var obj = new C2(); obj.call(); Output: c2 called Regards Don please bear with my noobishness, but i've been trying for many hours to understand what is going on behind this code: ** Code: function Person() { document.write('constructor: <br/>'+this.constructor); //displays Person constructor this.name = "Rob Roberson"; this.age = 31; } function Employee() { document.write('<br/>constructor: <br/>'+this.constructor); //displays Person constructor this.dept = "HR"; this.manager = "John Johnson"; } Employee.prototype = new Person(); var Ken = new Employee(); document.write('<br/>'+Ken.constructor); //displays Person constructor document.write('<br/>name:'+ Ken.name + '<br/>age:' + Ken.age + '<br/>dept:' + Ken.dept + '<br/>manager:' + Ken.manager ); //displays all properties correctly *** from what i've read, every object references a prototype. in this case, the Employee function will automatically reference a prototype with 'constructor' as its initial value. this command: Employee.prototype = new Person(); will replace the Employee function's prototype to an instance of Person. so now Employee function's prototype will contain both name and age properties, BUT, and this is where i get lost, ITS CONSTRUCTOR PROPERTY GETS REPLACED! so how does: var Ken = new Employee(); actually construct an instance of Employee if the reference to its constructor has been replaced by an instance of Person that only contains name and age properties? how is Ken ever initialized by Employee constructor? I posted this once, but it disappeared, and I have no notifications that I did anything wrong. I read the rules before posting and wasn't breaking any so I am not sure why it disappeared but here goes again. I am trying to learn Javascript (particularly OOP) from a series of screencasts by Douglas Crockford. I have developed a theoretical "game" to build to illustrate it to myself better, and learn by example. I must be misunderstanding how inheritance works, because my code is not producing the results I thought it would. Here is what I have, followed by an explanation of my understanding. Code: $(function() { function object(o) { function Funct() {} Funct.prototype = o; return new Funct(); } soldier = { pointsCost: 0, movement: "1 Infantry Block", validTargets: {}, weapons: { "Main Weapon": { "Weapon Type": "M4 Carbine", "Fire Range": 12 }, "Secondary Weapon": { "Weapon Type": "JCP .45", "Fire Range": 3 } } }; var rifleman = object(soldier); rifleman.pointsCost += 10; rifleman.validTargets.target1 = "Infantry" rifleman.weapons["Secondary Weapon"]["Weapon Type"] = ""; rifleman.weapons["Secondary Weapon"]["Fire Range"] = ""; var heavyGunner = object(soldier); heavyGunner.pointsCost += 20; heavyGunner.validTargets.target1 = "Infantry"; heavyGunner.validTargets.target2 = "Light Armor"; heavyGunner.weapons["Main Weapon"]["Weapon Type"] = "SAW M249"; heavyGunner.weapons["Main Weapon"]["Fire Range"] = 12; heavyGunner.weapons["Secondary Weapon"]["Weapon Type"] = ""; heavyGunner.weapons["Secondary Weapon"]["Fire Range"] = ""; var sniper = object(soldier); sniper.pointsCost += 30; sniper.validTargets.target1 = "Infantry"; sniper.weapons["Main Weapon"]["Weapon Type"] = "Savage .308"; sniper.weapons["Main Weapon"]["Fire Range"] = 20; sniper.weapons["Secondary Weapon"]["Weapon Type"] = "JCP .45"; sniper.weapons["Secondary Weapon"]["Fire Range"] = 3; var demolitions = object(soldier); demolitions.pointsCost += 30; demolitions.validTargets.target1 = "Infantry"; demolitions.validTargets.target2 = "Light Armor"; demolitions.validTargets.target3 = "Artilery"; demolitions.validTargets.target4 = "Structures"; demolitions.weapons["Main Weapon"]["Weapon Type"] = "SMAW MK153"; demolitions.weapons["Main Weapon"]["Fire Range"] = 16; demolitions.weapons["Secondary Weapon"]["Weapon Type"] = "M1014 Combat Shotgun"; demolitions.weapons["Secondary Weapon"]["Fire Range"] = 1; var infantry = { rifleman: rifleman, heavyGunner: heavyGunner, sniper: sniper, demolitions: demolitions }; console.log(infantry); }); I start by creating an object function that accepts an object passed in, and sets it to the prototype of a constructor (that would allow me to create a new object linked to, and inheriting from, the initial passed in object) I initialized a solider object literal, and pass that into the object function while creating 4 new objects (rifleman, heavyGunner, sniper, demolitions) These four should inherit from and customize upon the soldier object. The way I understood inheritance is that the new objects (example. rifleman) would inherit properties from the old object (i.e. soldier) and change or add properties, affecting only the new (rifleman) object but not changing the old(solider) object. this works ok somewhat in my example, until it comes to nested objects. In the above example I have objects as values for some Object's properties. (i.e. validTargets and weapons) When I change or add these, all of the new objects seem to inherit the last declarations, from demolitions, as if demolitions is actually changing that part of the soldier object so that the other's inherit those properties. From my viewpoint, I expected these values to not be changed and that the 4 infantry types had no link to each other, but only to the soldier object. I apparently misunderstood something, or coded something wrong. Some minor notes: -I will be updating most of the "string" values to be objects, so for instance, the validTargets value of "Infantry" would actually be the infantry object, stating that any of the 4 solider types would be a valid target. - I intend to create weapons as their own viable objects in the future, and pass those objects instead of "strings" - I intend to extend this (once this is working) to create an armor object that contains armor type units, similar in structure to the infantry object. - If I can get this all to work, I may make this into a "simple" dice style battle game. but that is way off, I just want to get this nesting of objects to work with inheritance for now. Thanks in advance for any help you can provide. Here is a link to the "live" example. (not much different there except if you have firebug you can see the console.log method showing the objects, and how they are inheriting in properly from my POV.) Link to Live example... Blue This is my first post. I am reading "Javascript The Good Parts" ~ The Method Invocation Pattern Page 28 and tried this, var myObject= { value:0, increment:function(inc){ this.value+= typeof inc==="number" ? inc:1; } } myObject.increment(2); alert(myObject.value); but alert(myObject.value); is returning a value of "2", when it should return "3". Can someone help? Reply With Quote 12-22-2014, 09:59 AM #2 rnd me View Profile View Forum Posts Visit Homepage Senior Coder Join Date Jun 2007 Location Urbana Posts 4,497 Thanks 11 Thanked 603 Times in 583 Posts 0+2=2, not 3; the code is working correctly. 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 |