JavaScript Prototype Chain Example
by Johnny Lee
HTML
<div id="message" />
CSS
body {
font-family: Verdana, Arial;
font-size: 1.1em;
}
JavaScript
function logMsg(str, noBreak) {
var msg = $('#message');
msg.append(str);
if (!noBreak) // if noBreak is asigned a value (any value), <br /> won't be output
msg.append('<br />');
}
function animalia () { // 動物界
this.kingdom = '動物界';
this.move = function() {
logMsg('動物走路');
}
}
function mammalia () { // 哺乳綱
this.class = '哺乳綱';
this.breastfeed = function() {
logMsg('哺乳動物授乳'); // 我知道只有母的哺乳動物才能授乳; 請讀者勿在此種細節上挑剔
}
}
mammalia.prototype = new animalia();
function homosapiens() { // 智人種
this.species = '智人種';
this.speak = function() {
logMsg('人類說話');
}
}
homosapiens.prototype = new mammalia();
var nurse1 = new homosapiens(); // nurse 有奶娘的意思, 不是指護士
logMsg(nurse1.kingdom);
logMsg(nurse1.class); // 把 class 這個字標注成關鍵字, 這是 jsFiddle 的問題, 不是我的問題
logMsg(nurse1.species);
nurse1.speak();
nurse1.breastfeed();
nurse1.move();