Skip to content

Commit 0f15ae4

Browse files
A Whimsical example on how prototypal inheritance works.
One of the things here that isn't plainly obvious is that every javascript function has access to a couple of built-in values - this, which more people are typically already familiar with, and also a pseudo-arraylike object, arguments. For more info just either google for 'javascript arguments' or check out an interesting blog post on the topic: http://javascriptweblog.wordpress.com/2011/01/18/javascripts-arguments-object-and-beyond/
1 parent 29c5c0d commit 0f15ae4

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

prototypal_inheritance.js

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
var gizmo = new_constructor(Object, function(id) {
2+
this.id = id;
3+
}, {
4+
toString: function () {
5+
return "gizmo " + this.id;
6+
}
7+
});
8+
9+
var hoozit = new_constructor(gizmo, function(id) {
10+
this.id = id;
11+
}, {
12+
test: function(id) {
13+
return this.id === id;
14+
}
15+
});
16+
17+
function new_constructor(extend, initializer, methods) {
18+
var func, prototype = Object.create(extend && extend.prototype);
19+
20+
if (methods) {
21+
methods.keys().forEach(function (key) {
22+
prototype[key] = methods[key];
23+
});
24+
}
25+
26+
func = function () {
27+
var that = Object.create(prototype);
28+
if (typeof initializer === 'function') {
29+
initializer.apply(that, arguments);
30+
}
31+
return that;
32+
}
33+
34+
func.prototype = prototype;
35+
prototype.constructor = func;
36+
return func;
37+
}

0 commit comments

Comments
 (0)