i using closure create object private , public methods. looks -
var dog = (function() { function dog() {} var size = 'big'; var _privatesaysize = function() { return 'i ' + size + ' dog.'; } dog.prototype.publicsaysize = function() { return _privatesaysize(); } return dog; })();
but have object has private functions , inherited object. possible in javascript?
you want 1 instance inherit private state of instance? sure can in javascript. first need define utility function:
function weakbind(functable, prototype, state) { return function () { return functable.apply(this, object.getprototypeof(this) === prototype ? [state].concat(array.prototype.slice.call(arguments)) : arguments); }; }
now can create our base class follows:
var dog = (function () { function dog() { if (this instanceof dog) { // constructor code } else return object.create(private); } var public = dog.prototype, private = object.create(public, { size: { value: "big" } }); public.saysize = weakbind(function (private) { return "i " + private.size + " dog."; }, public, private); return dog; }());
now can create dog follows:
var dog = new dog; alert(dog.saysize()); // big dog. alert(dog.size); // undefined
we can inherit private state follows:
var chihuahua = (function () { function chihuahua() { dog.call(this); } var private = dog(); object.defineproperty(private, { size: { value: "small" } }); var public = chihuahua.prototype = object.create(dog.prototype); public.saysize = weakbind(public.saysize, public, private); return chihuahua; }());
now can create chihuahua follows:
var chi = new chihuahua; alert(chi.saysize()); // small dog. alert(chi.size); // undefined
see demo: http://jsfiddle.net/b3eyn/
note: wrote answer show it's possible inherit private state in javascript. advise not use pattern. if design code won't need inherit private state in first place.
Comments
Post a Comment