Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Protection of the function code from inspection
// basic implementation
function protect ( fn ) {
fn.toString = fn.toLocaleString = fn.toSource = function () {
return 'function ' + fn.name + '() { [native code] }';
};
}
// but indirect call still available, so fix it
var protect = (function () {
// function can be reassign with different name, so use functions itself instead of string names
// due to browser optimizations it isn't an overhead probably
var protectedFunctions = [];
Function.prototype.toString.call =
Function.prototype.toSource.call =
Function.prototype.toLocaleString.call =
Function.prototype.toString.apply =
Function.prototype.toSource.apply =
Function.prototype.toLocaleString.apply = function ( thisArg ) {
if ( ~protectedFunctions.indexOf(thisArg) ) {
return 'function ' + thisArg.name + '() { [native code] }';
}
};
return function ( fn ) {
if ( !~protectedFunctions.indexOf(fn) ) {
protectedFunctions.push(fn);
fn.toString = fn.toLocaleString = fn.toSource = function () {
return 'function ' + fn.name + '() { [native code] }';
};
}
};
}());
// some function that should be protected
function apiMethod () { /* code here */ }
// protection
protect(apiMethod);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.