Last active
December 11, 2015 11:19
-
-
Save bennybennet/4593122 to your computer and use it in GitHub Desktop.
Trying to implement a usefull and easy-to-read way for declaring classes in JavaScript.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* Simple JavaScript Inheritance | |
* First draft! | |
* @author Benny Bennet Jürgens (http://ben.nyben.net) | |
* CC-by-sa 3.0 - please provide my name and url | |
*/ | |
;(function() { | |
"use strict"; | |
this.BBClass = function(ctor, proto) { | |
ctor.prototype = proto || {}; | |
ctor.prototype.constructor = ctor; | |
ctor.extends = function(parent) { | |
function ChildBB() { | |
parent.prototype.constructor.apply(this, arguments); | |
ctor.apply(this, arguments); | |
}; | |
ChildBB.prototype = ( typeof Object.create !== 'function') ? | |
(function(parent) { | |
function F() {}; | |
F.prototype = parent.prototype; | |
var prototype = new F(); | |
prototype.constructor = ChildBB; | |
return prototype; | |
})(parent) | |
: Object.create(parent.prototype, { constructor: { value: ChildBB, enumerable: false }}); | |
return ChildBB; | |
} | |
return ctor; | |
} | |
}).call(this); | |
var Person = BBClass(function(isDancing) { | |
console.log("person"); | |
this.dancing = isDancing; | |
}); | |
Person.prototype.dance = function() { | |
return this.dancing; | |
}; | |
var Ninja = BBClass(function(isDancing) { | |
console.log("ninja"); | |
}).extends(Person); | |
Ninja.prototype.swingSword = function() { | |
return true; | |
}; | |
Ninja.prototype.arraytest = [1,2,3,4]; | |
var p = new Person(true); | |
var n = new Ninja(false); | |
Person.prototype.test2 = function() { console.log("test2 bestanden"); }; | |
console.log(n.arraytest); | |
console.log(p.dance()); | |
console.log(n.dance()); | |
console.log(n.swingSword()) | |
p.test2(); | |
n.test2(); | |
console.log("inherit ok?") | |
console.log( p instanceof Object); | |
console.log( p instanceof Person); | |
console.log( p instanceof Person && p instanceof Object && n instanceof Ninja && n instanceof Person && n instanceof Object); | |
=> person | |
=> person | |
=> ninja | |
=> [1,2,3,4] | |
=> true | |
=> false | |
=> true | |
=> test2 bestanden | |
=> test2 bestanden | |
=> inherit ok? | |
=> true | |
=> true | |
=> true |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Improved performance of object definition and addes mixins (aka jQuery.extend - WIP). Latest performance measures: http://jsperf.com/goog-inherit-vs-simple-inherit/6