Created
December 21, 2010 15:26
-
-
Save npup/750053 to your computer and use it in GitHub Desktop.
Svin, VildSvin och Stior
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** ----------------------------------------------------- | |
* Djur | |
* | |
*/ | |
function Svin(name) { | |
this.name = name; | |
this.type = 'Svin'; | |
} | |
Svin.toString = function () { | |
}; | |
Svin.prototype.toString = function () { | |
return this.name + ' (' + this.type + ')'; | |
}; | |
function VildSvin(name) { | |
this.name = name; | |
this.type = 'VildSvin'; | |
} | |
VildSvin.prototype = new Svin(); | |
/** ----------------------------------------------------- | |
* Byggnader | |
* | |
*/ | |
function Stia() { | |
this.uid = Stia.uid++; | |
this.objects = []; | |
} | |
Stia.uid = 0; | |
Stia.okTypes = [Svin]; | |
Stia.prototype.add = function (obj) { | |
var okType = false, len, idx, type; | |
for (idx=0, len=Stia.okTypes.length; idx<len; ++idx) { | |
type = Stia.okTypes[idx]; | |
if (obj instanceof type) { | |
okType = true; | |
break; | |
} | |
} | |
if (!okType) throw Error('Obj ' + obj + ' could not be added to Stia ['+this.uid+']. Is type: ' + typeof obj); | |
this.objects.push(obj); | |
}; | |
Stia.prototype.toString = function () { | |
var len = this.objects.length | |
, result = 'Stia ' + this.uid + ' has ' + len + ' objekt'; | |
if (len>0) { | |
result += ':\n -'; | |
result += this.objects.join('\n -'); | |
} | |
return result; | |
}; | |
/** ----------------------------------------------------- | |
* Test | |
* | |
*/ | |
var | |
// Djur | |
s1 = new Svin('Olle') | |
, s2 = new Svin('Pelle') | |
, s3 = new Svin('Gurgel') | |
, v1 = new VildSvin('Putte') | |
, v2 = new VildSvin('Efraim') | |
, v3 = new RegExp(/will-blow/) | |
// byggnader | |
, stia1 = new Stia() | |
, stia2 = new Stia(); | |
// Skriva ut ett objekt | |
function p(o) {console.log(o.toString());} | |
// Skriv ut skapade svin och byggnader | |
p(s1); | |
p(s2); | |
p(s3); | |
p(v1); | |
p(v2); | |
p(v3); | |
p(stia1); | |
p(stia2); | |
// Lägg till lite grejs till stiorna (catch för att fånga dumma objektet) | |
try { | |
stia1.add(s3); | |
stia1.add(s2); | |
stia1.add(s1); | |
stia2.add(v1); | |
stia2.add(v2); | |
stia1.add(v3); | |
} | |
catch (e) { | |
console.log(e.message); | |
} | |
// Skriv ut stiorna igen | |
p(stia1); | |
p(stia2); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment