Skip to content

Instantly share code, notes, and snippets.

@lordvlad lordvlad/index.js forked from gavinengel/magic-globals.js
Last active Jun 14, 2018

Embed
What would you like to do?
/*
* sets globals __line, __file, __ext, __dir and __function
* influences
* http://goo.gl/wwjGVV and http://goo.gl/umq4s1
* https://gist.github.com/gavinengel/8572856
* https://github.com/kvz/phpjs/tree/master/experimental/language
* todo: __method, __class/__constructor
*/
// begin setting magic properties into global (required for other functions)
Object.defineProperty(global, '__stack', {
get: function(){
var orig = Error.prepareStackTrace;
Error.prepareStackTrace = function(_, stack){ return stack; };
var err = new Error;
Error.captureStackTrace(err, arguments.callee);
var stack = err.stack;
Error.prepareStackTrace = orig;
return stack;
}
});
/**
* returns line number when placing this in your code: __line
*/
Object.defineProperty(global, '__line', {
get: function(){
return __stack[1].getLineNumber();
}
});
/**
* return filename (without directory path or file extension) when placing this in your code: __file
*/
Object.defineProperty(global, '__file', {
get: function(){
return __filename.split('/').slice(-1)[0].split('.').slice(0, -1).join('.');
}
});
/**
* return file extension (without preceding period) when placing this in your code: __ext
*/
Object.defineProperty(global, '__ext', {
get: function(){
return __filename.split('.').slice(-1)[0];
}
});
/**
* return current function
*/
Object.defineProperty(global, '__function', {
get: function(){
return arguments.callee.caller && arguments.callee.caller.name || '(anonymous)';
}
});
// end setting magic properties into global
{
"name": "extglobals",
"version": "0.0.1",
"description": "extends the global object with __ext, __line and __function",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"repository": {
"type": "git",
"url": "https://gist.github.com/ec81834ddff73aaa1ab0.git"
},
"keywords": [
"global",
"magic",
"properties"
],
"author": "lordvlad",
"license": "MIT"
}
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.