-
-
Save DavidBruant/c7d4947b41936680810d to your computer and use it in GitHub Desktop.
Protected protocol
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
"use strict"; | |
Function.prototype.curry = function(){ | |
var bindArgs = [undefined].concat(Array.prototype.slice.call(arguments, 0)); | |
console.log('bindArgs', bindArgs); | |
return Function.prototype.bind.apply(this, bindArgs); | |
} | |
function makeProtectedStore(){ | |
var wm = new WeakMap(); | |
return function(o){ | |
console.log('typeof o', typeof o); | |
var p = wm.get(o); | |
if(!p){ | |
p = {}; | |
wm.set(o, p); | |
} | |
return p; | |
}; | |
} | |
// add a cache? so that makeConstructorWithProtected(C) === makeConstructorWithProtected(C)? | |
function makeConstructorWithProtected(C){ | |
var prot = makeProtectedStore(); | |
var boundC = C.curry(prot); | |
Object.defineProperty(boundC, 'originalConstructor', { | |
value: C | |
}); | |
Object.defineProperty(boundC, 'prototype', { | |
configurable: false, | |
get: function(){return C.prototype;}, | |
set: function(v){C.prototype = v;} | |
}); | |
return boundC; | |
} | |
function inherit(constr, parent){ | |
var prot = makeProtectedStore(); | |
var boundParent = function(){ | |
return parent.originalConstructor.apply(this, [prot].concat(Array.prototype.slice.call(arguments, 0))) | |
}; | |
return constr.curry(prot, boundParent); | |
} | |
// PERSON | |
(function(global){ | |
function Person(Protected, name){ | |
console.log('this in Person', this); | |
Protected(this).secret = String(Math.random()).substr(2); | |
console.info("person's secret", Protected(this).secret, "...shhhhhhh!!!..."); | |
this.name = name; | |
} | |
global.Person = makeConstructorWithProtected(Person); | |
})(this); | |
// COMPUTER SAVVY PERSON | |
(function(global){ | |
function ComputerSavvyPerson(Protected, Super, name, favoriteLanguage){ | |
console.log('this in ComputerSavvyPerson', this); | |
Super.call(this, name); | |
this.favoriteLanguage = favoriteLanguage; | |
this.getSecretFirstLetter = function(){ | |
return Protected(this).secret[0]; | |
} | |
} | |
global.ComputerSavvyPerson = inherit(ComputerSavvyPerson, Person); | |
})(this); | |
// CLIENT CODE | |
var d = new Person('David'); | |
console.log('d.name:', d.name); | |
console.log(d); | |
var db = new ComputerSavvyPerson('David Bruant', 'JavaScript'); | |
console.log('db.name:', db.name); | |
console.log('db.favoriteLanguage:', db.favoriteLanguage); | |
console.log('first letter secret', db.getSecretFirstLetter()); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment