Murphy.js
A functional interface for information hiding and inheritance.
Murphy's Law: If there are two or more ways to do something, and one of those ways can result in a catastrophe, then someone will do it.
JavaScript does not provide an effective mechanism for encapsulating data.
"Classes" (and, in ECMAScript 6, the class
keyword) do not provide syntactic
support for private or protected fields.
{ this_name = name; } { console; } { this_name = name;}Personprototype { console;}; var joe = 'Joe';console; // "Joe"
It is a major shortcoming that _name
is accessible from the outside, because
there is no reason for it to be, and it would be unreliable for a programmer to
depend on its accessibility.
To achieve privacy, one must use var
.
{ var name = optionsname; this { console; };}
But the data cannot be shared by inheritors.
{ this { // ReferenceError: name is not defined console; }; }
We want "protected" data that can be accessed by the lineage but is inaccessible to the outside world.
Meet Murphy:
var makeConstructor = ;var makePerson = ;var makeMayor = ; var person = ;person; // Hi, my name is "Joe".console; // undefined var mayor = ;mayor; // Good day, citizen! My name is "Bob".console; // undefined
With Murphy, you don't need "prototypal" constructors, new
, this
, or even
the class
keyword or () => {}
("fat arrow" functions). All you need is
makeConstructor
and function
.
With Murphy, you can build extensible interfaces that don't expose private
data. Thanks to encapsulation, the things that can go wrong when
_pinkyPromises
are $$violated
, cannot go wrong.
Installation
Browser:
bower install --save murphy
Node:
npm install --save murphy
Usage
Via browser global:
var makeConstructor = ;
AMD:
;
CommonJS:
var murphy = ;var makeConstructor = ;
Development
To run tests in Node.js:
npm test
To run tests in a browser, open test.html
.
License
MIT.