Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
I am trying to create some objects and wrapper classes to simplify some form checking methods. I have researched the standard routine for JavaScript inheritance but I am getting a rather odd error when running my code. Here is the gist:
function FooParent (a){
    this.prop = a;
    this.val = a.value;//*
}
var elem = new FooParent(document.getElementById("someDomElement");
alert(elem.val);
//alerts the value of the form element no prob!
If I then add this block to the same code:
function FooKid (a, b) {
    FooParent.call(this, b);
    this.kidProp = b;
}
FooKid.prototype = new FooParent();
FooKid.prototype.constructor = FooKid;
var elem2 = new FooKid(document.getElementById("someDomElement");
alert(elem2.val);
//the variable declaration in the last two lines is inconsequential, the code breaks on line 3 when I run it after adding the last block. 
The error that firebug gives me is that in the parent object this.val = a.value; is now undefined when it worked prior to trying to inherit from it. I also tried... this.val = this.prop.value, and this.val = prop.value (all should point to the same thing So in conclusion, my question is: why is this code breaking? Where is the bug?
Posted 15-Dec-12 0:30am
JonC04314
Comments
Mohibur Rashid at 15-Dec-12 7:13am
   
You have to coding error
on line 6 of first part of code
on line 6 of second part of code
 

FooParent only receive one parameter but you are calling it with two parameter
 
and so on....
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 1

inheritance in javascript:
 
if (typeof Object.create !== 'function') {
	Object.create = function (o) {
		function F() { }
		F.prototype = o;
		return new F();
	};
}
 
var newObject1 = Object.create({key1:'valuekke'});
var newObject2 = Object.create(newObject1);
 

  Permalink  
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 2

In you code FooParent expects a param 'a'
In your line...
new FooParent();
...you haven't provided this param.
  Permalink  

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
0 OriginalGriff 319
1 Kornfeld Eliyahu Peter 265
2 Maciej Los 249
3 BillWoodruff 205
4 Sergey Alexandrovich Kryukov 175
0 OriginalGriff 5,107
1 DamithSL 4,157
2 Maciej Los 3,595
3 Kornfeld Eliyahu Peter 3,450
4 Sergey Alexandrovich Kryukov 2,741


Advertise | Privacy | Mobile
Web04 | 2.8.141216.1 | Last Updated 20 Dec 2012
Copyright © CodeProject, 1999-2014
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100