Created
June 20, 2017 00:49
-
-
Save mLuby/ee37b813e9da84dd6aadd10487410fad to your computer and use it in GitHub Desktop.
Two ways to get private methods and data in JS.
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" | |
console.log("––– Con –––") | |
function Con () { | |
let privateData = 123 | |
private_makeMethodsPublic(this, [public_connect]) | |
function public_connect (username, password) { | |
privateData = username + password | |
} | |
function private_makeMethodsPublic (context, methods) { | |
methods.forEach(method => context[method.name] = method) | |
} | |
} | |
const con = new Con() | |
console.log("Shows public methods:", con) | |
console.log("Public methods callable:", con.public_connect) | |
console.log("Private methods uncallable:", con.private_makeMethodsPublic) | |
console.log("No access to private state:", con.privateData) | |
console.log("––– Con2 –––") | |
const Con2 = publicizeClassMethods(class _Con { | |
constructor () { | |
this.privateData = 123 | |
} | |
public_connect (username, password) { | |
this.privateData = username + password | |
} | |
private_method (context, methods) { | |
} | |
}, ["public_connect"]) | |
function publicizeClassMethods (clas, methodNames) { | |
const instance = new clas() | |
return function () { return methodNames.reduce((obj, methodName) => (obj[methodName] = instance[methodName], obj), {}) } | |
} | |
const con2 = new Con2() | |
console.log("Shows public methods:", con2) | |
console.log("Public methods callable:", con2.public_connect) | |
console.log("Private methods uncallable:", con2.private_method) | |
console.log("No access to private state:", con2.privateData) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment