JavaScript - *please Can Someone Review* Writing An Object Constructor With Inheritance
Similar TutorialsI 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 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. What are the benefits of prototypal inheritance over classical inheritance?
What are the benefits of prototypal inheritance over classical inheritance?
hi, 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 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> 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. 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; 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 downloaded "Unique Rate and Review" and have not been able to get the script working. Apperantly it's supposed to be easy so I feel quite dumb but can anyone please throw me a bone here?? This is my first experience with PHP and Javascript so please if you can help, speak in simple terms. My problem is that when anyone enters a review it says "You have already reviewed" and doesnt let anyone post. Take A look I have tried everything I can think of. Thank you. http://www.localkaraokeshows.com/cou...asallerate.php 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 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 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 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, 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. 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? 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 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 |