Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

started code an resue patterns

  • Loading branch information...
commit d458abcca00671d1b0973632d36fd7de960f15d2 1 parent fdd0190
@shichuan shichuan authored
Showing with 79 additions and 0 deletions.
  1. +79 −0 code-reuse-patterns/klass.html
View
79 code-reuse-patterns/klass.html
@@ -0,0 +1,79 @@
+<!doctype html>
+<html lang="en">
+<head>
+<title>JavaScript Patterns</title>
+<meta charset="utf-8">
+</head>
+<body>
+<script>
+/* Title: Klass
+ Description: generally a pattern that should be avoided unless one is more comfortable with class than prototype
+*/
+
+var klass = function (Parent, props) {
+
+ var Child, F, i;
+
+ // 1.
+ // new constructor
+ Child = function () {
+ if (Child.uber && Child.uber.hasOwnProperty("__construct")) {
+ Child.uber.__construct.apply(this, arguments);
+ }
+ if (Child.prototype.hasOwnProperty("__construct")) {
+ Child.prototype.__construct.apply(this, arguments);
+ }
+ };
+
+ // 2.
+ // inherit
+ Parent = Parent || Object;
+ F = function () {};
+ F.prototype = Parent.prototype;
+ Child.prototype = new F();
+ Child.uber = Parent.prototype;
+ Child.prototype.constructor = Child;
+
+ // 3.
+ // add implementation methods
+ for (i in props) {
+ if (props.hasOwnProperty(i)) {
+ Child.prototype[i] = props[i];
+ }
+ }
+
+ // return the "class"
+ return Child;
+};
+
+var Man = klass(null, {
+ __construct: function (what) {
+ console.log("Man's constructor");
+ this.name = what;
+ },
+ getName: function () {
+ return this.name;
+ }
+});
+
+var first = new Man('Adam'); // logs "Man's constructor"
+first.getName(); // "Adam"
+
+var SuperMan = klass(Man, {
+ __construct: function (what) {
+ console.log("SuperMan's constructor");
+ },
+ getName: function () {
+ var name = SuperMan.uber.getName.call(this);
+ return "I am " + name;
+ }
+});
+
+var clark = new SuperMan('Clark Kent');
+clark.getName(); // "I am Clark Kent"
+
+console.log(clark instanceof Man); // true
+console.log(clark instanceof SuperMan); // true
+</script>
+</body>
+</html>
Please sign in to comment.
Something went wrong with that request. Please try again.