View Full Version : Custom Object (inheritance?)
vkidv
08-02-2005, 02:59 PM
Hi.
function one(n) {
this.n = n ;
this.list = new two() ;
this.list() ;
}
function two() {
alert(this.n) ;
}
hi = new one(50) ;
How do I make two able to access all of one's properties/methods?
martin_narg
08-02-2005, 03:30 PM
A good way is to create a method for the object you have created, this is shown below
function one(n) { // create the object
this.n = n ;
}
one.prototype.two = function() { // create a new method for the one object
alert(this.n);
}
var hi = new one(50) ; // create an instance of the object
hi.two(); // this would alert 50
Hope this helps
m_n
dumpfi
08-02-2005, 04:29 PM
This is the only way I know to achieve something like "inheritance" in JavaScript:
function one(n) {
this.n = n;
}
function two() {
this.getN = function() { return this.n; }
this.setN = function(n) { this.n = n; }
}
one.prototype = new two();
hi = new one(50);
alert(hi.getN());
hi.setN(100);
alert(hi.getN());dumpfi
function one(n) {
this.n = n;
}
function two() {
alert(this.n);
}
var oOne = new one(5);
two.call(oOne);
glenngv
08-03-2005, 01:27 PM
http://crockford.com/javascript/inheritance.html
vkidv
08-03-2005, 07:56 PM
Thanks for the replies everyone.
I think I've cracked it, I don't think it's inheritance but it works as I wanted it to.
function Animal( Name, Age ) {
this.Name = Name ;
this.Age = Age ;
this.Statistics = new Statistics(this) ;
this.Statistics.Calculate() ;
}
function Statistics( Parent ) {
this.Parent = Parent ;
this.Calculate = Calculate ;
}
function Calculate() {
this.Weight = this.Parent.Age * 2 ;
}
var myFish = new Animal("Geoffrey",.5) ;
alert(myFish.Statistics.Weight) ;
EDIT: Before anybody asks, this isn't my real code =P heh. :p Its just a made up example, so I don't know why Weight is twice the age.
Does 'this' copy the whole object or is it just a reference/pointer?
Is there any more elegant/more efficient ways to do the above?
Thanks for the link glenn, and interesting code from dumpfi, Narg and jkd. I think the original problem was, I didn't know what I wanted, I wasn't sure if it was inheritance or not.
vBulletin® v3.8.2, Copyright ©2000-2012, Jelsoft Enterprises Ltd.