Created
March 17, 2013 03:45
-
-
Save edom18/5179466 to your computer and use it in GitHub Desktop.
クラス風継承を今どきの書き方でやってみる ref: http://qiita.com/items/200ae66bd18011bda377
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
(function (win, doc, exports, undefined) { | |
'use strict'; | |
var fnTest = /xyz/.test(function(){xyz;}) ? /\b_super\b/ : /.*/; | |
function Class() { /* noop. */ } | |
Class.extend = function (props) { | |
var SuperClass = this; | |
function Class() { | |
if (typeof this.init === 'function') { | |
this.init.apply(this, arguments); | |
} | |
} | |
Class.prototype = Object.create(SuperClass.prototype, { | |
constructor: { | |
value: Class, | |
writable: true, | |
configurable: true | |
} | |
}); | |
Object.keys(props).forEach(function (key) { | |
var prop = props[key], | |
_super = SuperClass.prototype[key], | |
isMethodOverride = (typeof prop === 'function' && typeof _super === 'function' && fnTest.test(prop)); | |
if (isMethodOverride) { | |
Class.prototype[key] = function () { | |
var ret, | |
tmp = this._super; | |
Object.defineProperty(this, '_super', { | |
value: _super, | |
configurable: true | |
}); | |
ret = prop.apply(this, arguments); | |
Object.defineProperty(this, '_super', { | |
value: tmp, | |
configurable: true | |
}); | |
return ret; | |
}; | |
} | |
else { | |
Class.prototype[key] = prop; | |
} | |
}); | |
Class.extend = SuperClass.extend; | |
return Class; | |
}; | |
exports.Class = Class; | |
}(window, window.document, window)); |
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
(function (win, doc, exports, undefined) { | |
'use strict'; | |
var Person = Class.extend({ | |
init: function () { | |
console.log('hoge'); | |
} | |
}); | |
var Ninja = Person.extend({ | |
init: function () { | |
this._super(); | |
console.log('foo'); | |
} | |
}); | |
var Samurai = Ninja.extend({ | |
init: function () { | |
this._super(); | |
console.log('bar'); | |
}, | |
_super: 'super!' | |
}); | |
var p = new Person(); | |
var n = new Ninja(); | |
var s = new Samurai(); | |
console.log(s._super); | |
}(window, window.document, window)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment