If a Javascript object has a property which holds a reference to a function, can I get that property name from within the function itself? -



If a Javascript object has a property which holds a reference to a function, can I get that property name from within the function itself? -

so:

class="lang-js prettyprint-override">var obj = { 'key': function() { // 'key' here } }; obj.key();

example:

http://plnkr.co/edit/tsuz6wy1qivuoie3qsuv?p=preview

class="lang-js prettyprint-override">var logger = { 'warn': function(msg) { var loglvl = 'warn'; // <-- want string 'warn' right here console.log('[', loglvl, ']', msg); } }; logger.warn('computer exploding.'); // => [ warn ] computer exploding.

i can think of convoluted method of using named function , searching this value of function:

http://plnkr.co/edit/ihu087timhzca2ebjdua?p=preview

class="lang-js prettyprint-override">var logger = { 'warn': function func(msg) { console.log('[', _.invert(this)[func], ']', msg); } }; logger.warn('computer exploding.');

is there easy way this?

update: here's more detail on why i'm asking.

this angular application. here's list of presets. preset has name , 2 numbers: https://github.com/wideshanks/breatherbar/blob/rmui/app.js#l372

these rendered list items on front end end: https://github.com/wideshanks/breatherbar/blob/rmui/index.html#l42

when clicks on list item, want add together new default pattern list , set name/two numbers what's in preset.

the presets functions add together new patterns. 2 numbers defined within function body, name of preset outside function: it's property name in $scope.presets: https://github.com/wideshanks/breatherbar/blob/rmui/app.js#l359

probably need rethink whole thing, because way did has ended convoluted.

you rig this:

var loglevels = [ "trace", "debug", "info", "warn", "error" ]; var logger = loglevels.reduce(function(logger, level) { logger[level] = function(msg) { console.log("[" + level + "] " + msg); }; homecoming logger; }, {});

that iterates through list of (made-up of course) log levels, adding function each. function relies on closure created around .reduce() callback. each function behaves according logger property it's associated, it's not intrinsically bound way.

javascript

Comments

Popular posts from this blog

Delphi change the assembly code of a running process -

json - Hibernate and Jackson (java.lang.IllegalStateException: Cannot call sendError() after the response has been committed) -

C++ 11 "class" keyword -