JavaScript Inheritance
Blogs20132013-11-19
JavaScript Inheritance
I summary JavaScript Inheritance methods, originally from Stoyan Stefanov.
| Ā | function Constructor(){}; new Constructor(); | object = {}; |
|---|---|---|
| prototype | Child.prototype = new Parent(); | Ā |
| Child.prototype = Parent.prototype; | Ā |
| function extend(Child, Parent) { var F = function() {}; F.prototype = Parnt.prototype; Child.prototype = new F(); Child.prototype.constructor=Child; }
| Ā | | prototype + attributes copy |
function extend2(Child, Parent) { var p = Parent.prototype; var c = Child.prototype; for (var i in p) { c[i] = p[i]; } }
| Ā | | attributes copy | Ā |
function extendCopy(p) { var c = {}; for (var i in p) { c[i] = p[i]; } return c; }
| | attributes copy | Ā |
function deepCopy(p, c) { var c = c || {}; for (var i in p) { if(typeof p[i] === āobjectā) { c[i] = (p[i].constructor===Array)? [] : {}; deepCopy(p[i], c[i]); } else { c[i] = p[i]; } } return c; }
| | prototype | Ā |
function object(o) { function F() {}; F.prototype = o; return new F(); }
| | prototype + attributes copy | Ā |
function objectPlus(o, attrs) { var n = null; function F() {}; F.prototype = o; n = new F(); for(var i in attrs) { n[i] = attrs[i]; } return n; }
| | attributes copy | Ā |
function multi() { var n = {}, stuff, j = 0, len = arguments.length; for (j = 0; j < len; j++) { stuff = arguments[j]; for (var i in stuff) { n[i] = stuff[i]; } } return n; }
| | prototype | Ā |
function parasite(victim) {
var that = object(victim);
that.more = 1;
return that;
}
| | Ā |
function Child() { Parent.apply(this.arguments); }
| Ā | | prototype + attributes copy |
function Child() { Parent.apply(this, arguments); } extend2(Child, Parent);
| Ā |
