Thu, 28 Mar 2013
JavaScriptでのクラスの実装の隠蔽
Tweet
こんなふうにしたらJavaScriptでクラスの実装を隠蔽できるんじゃないかなあと思った。
| Comments on this entryfunction() { // method list var methods = ["methodA", "methodB"]; // implementation class var Impl = function() { ... }; Impl.prototype = { methodA: function() { ... }, methodB: function() { ... } }; // the (interface) class var Foo = function() { var impl = new Impl(arguments); // delegate to the implementation class this.call_method = function(name, args) { return impl[name].apply(impl, args); }; }; // define method interface methods.forEach(function(name) { Foo.prototype[name] = function() { return this.call_method(name, arguments); }; }); return Foo; };