Skip to content

Instantly share code, notes, and snippets.

@jackw
Created October 15, 2013 07:24
Show Gist options
  • Save jackw/6987812 to your computer and use it in GitHub Desktop.
Save jackw/6987812 to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>JS Bin</title>
</head>
<body>
</body>
</html>
// Defining Methods!
function createElem(elemType, txt) {
txt = txt || null;
var elem = document.createElement(elemType);
if (txt !== null) {
var t = document.createTextNode(txt);
elem.appendChild(t);
}
document.body.appendChild(elem);
}
// example 1
function speak(line) {
createElem('p', "The " + this.adjective + " rabbit says '" + line + "'");
}
function run (from, to) {
createElem('p', "The " + this.adjective + " rabbit runs from " + from + " to " + to + ".");
}
var whiteRabbit = {
adjective: "white",
speak: speak
};
var fatRabbit = {
adjective: "fat",
speak: speak
};
whiteRabbit.speak("Holy shit I should do the daz door step challenge");
fatRabbit.speak("Stop fattening me up you bastard.");
speak.apply(fatRabbit, ["Get in my belly..."]);
speak.call(fatRabbit, "Burp!");
run.apply(whiteRabbit,["A", "B"]);
run.call(fatRabbit, "the cupboard", "the fridge");
// example 2
function Rabbit(adjective) {
this.adjective = adjective;
this.speak = function(line) {
createElem('p', "The " + this.adjective + " rabbit says '" + line + "'");
};
}
// Prototypes! :o
Rabbit.prototype.eat = function(food) {
createElem('p', "The " + this.adjective + " eats " + food);
};
Rabbit.prototype.move = function(direction, distance) {
createElem('p', "The " + this.adjective + " rabbit moved " + distance + " steps " + direction);
};
var killerRabbit = new Rabbit('killer');
killerRabbit.speak("GRAAAAAAHHHH!");
killerRabbit.eat("white rabbit");
killerRabbit.move("north", "10");
// example 3
function makeRabbit(adjective) {
return {
adjective : adjective,
speak : function(line) {
createElem('p', "The " + this.adjective + " rabbit says '" + line + "'");
},
run : function(from, to) {
createElem('p', "The " + this.adjective + " rabbit runs from " + from + " to " + to + ".");
}
};
}
var blackRabbit = makeRabbit("black");
blackRabbit.speak("I\'m as dark as night and I\'ll rip your heart in two!");
var veryFatRabbit = makeRabbit("very fat");
veryFatRabbit.run("killer rabbit", "his house");
// example 4
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment