Skip to content

Instantly share code, notes, and snippets.

@htatche
Last active January 4, 2016 22:18
Show Gist options
  • Save htatche/8686520 to your computer and use it in GitHub Desktop.
Save htatche/8686520 to your computer and use it in GitHub Desktop.
A Pen by Hervé.

Playing around with namespaces, prototype inheritance, and anonymous functions

Here I will throw the code that comes down from the top of my head in my spare time, just to have fun !

A Pen by Hervé on CodePen.

License.

// Namespace "ns" with class (object) extension
var ns = {
Programmer: function() {
this.likes = function() {
console.log("Iron maiden");
}
},
CoolProgrammer: function() {
var programmer = new ns.Programmer();
programmer.likes();
}
};
ns.CoolProgrammer.prototype.doesnotlike = function() { console.log("Rules") };
herve = new ns.CoolProgrammer();
herve.doesnotlike();
// Anonymous function with method rewrite
(function Printer(c, d) {
c.log = function (str) { d.write("<b>" + str + "</b>") };
c.log("Splashing ink !");
}
)(console, document);
//Module parttern (simplest example ever)
var module = (function () {
//private
return {
//public
}
}());
// Inheriting an object through the prototype property
var Human = function() {
this.iron = function() {
return console.log("Iron power !");
}
return this;
};
var Child = function() {
}
Child.prototype = new Human();
var child = new Child();
child.iron();
// Accesing parent instance scope from child instance
var Parent = function() {
this.name = "Parent";
this.Child = Child;
this.Child.prototype.parent = this;
}
var Child = function() {
}
var parent = new Parent();
var child = new parent.Child();
console.log(child.parent.name);
// Inheriting properties
var Status = function(args) {
var self = this;
var args = args || {};
self.setBodyParams = function(args) {
self.body = args.body;
}
self.setBodyParams(args);
return self;
};
var Question = function(args) {
var self = this;
var args = args || {};
self.setBodyParams(args);
return self;
}
Question.prototype = new Status();
Question.prototype.constructor = Question;
var question = new Question({"body": "IAMA BODY"});
console.log(question.body);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment