How do get the name of a calling function in Javascript? - javascript

Consider the following example.
var obj = function(){};
function apply(target, obj) {
if (target && obj && typeof obj == "object") {
for (var prop in obj) {
target[prop] = obj[prop];
}
}
return target;
}
apply(obj.prototype, {
firstFunction: function (){
this.secondFunction();
},
secondFunction: function (){
// how do I know what function called me here?
console.log("Callee Name: '" + arguments.callee.name + "'");
console.log("Caller Name: '" + arguments.callee.caller.name + "'");
}
});
var instance = new obj();
instance.firstFunction();
UPDATE
Both answers are really awesome. Thank you. I then looked into the problem of calling a recursive, or parent function within an object and found a solution here. This would allow me to retrieve the function name without using the arguments.callee/caller properties.
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/function

A function's name is an immutable property of that function, set in the initial function expression.
var notTheName = function thisIsTheName() { ... }
someObj.stillNotTheName = function stillTheName() { ... }
If your function expression does not have a name, there is (unsurprisingly) no way to identify it by name. Assigning a function to a variable does not give it a name; if that were the case, you could not determine the name of an expression assigned to multiple variables.
You should set firstFunction's name property by expressing it as
firstFunction: function firstFunction(){
this.secondFunction();
}
Also, arguments.callee is deprecated. See Why was the arguments.callee.caller property deprecated in JavaScript? for a very good explanation of the history of arguments.callee.

Give name to the functions
like:
var obj = function(){};
function apply(target, obj) {
if (target && obj && typeof obj == "object") {
for (var prop in obj) {
target[prop] = obj[prop];
}
}
return target;
}
apply(obj.prototype, {
firstFunction: function firstFunction(){
this.secondFunction();
},
secondFunction: function secondFunction(){
// how do I know what function called me here?
console.log("Callee Name: '" + arguments.callee.name + "'");
console.log("Caller Name: '" + arguments.callee.caller.name + "'");
}
});
var instance = new obj();
instance.firstFunction();
take a look on this question

Related

Getting Object Key Name from inside function?

Say I have an object like below:
var obj = {};
obj.test = function() { console.log(?); }
Is there anyway to print out "test", the key that this function is value of, but not know the obj name in advance?
Not really. Relationships in JS are one-way.
You could search for a match…
var obj = {};
obj.not = 1;
obj.test = function() {
var me = arguments.callee;
Object.keys(obj).forEach(function(prop) {
if (obj[prop] === me) {
console.log(prop);
}
});
};
obj.test();
But look at this:
var obj = {};
obj.not = 1;
obj.test = function() {
var me = arguments.callee;
Object.keys(obj).forEach(function(prop) {
if (obj[prop] === me) {
console.log(prop);
}
});
};
obj.test2 = obj.test;
obj.test3 = obj.test;
window.foo = obj.test;
obj.test();
The same function now exists on three different properties of the same object … and as a global.
Might be a bit of a convoluted solution, but this might be useful -
You can have a method that will add functions to your object at a specific key. Using the bind method, we can predefine the first argument to the function to be the key that was used to add it.
The function that I am adding to the key is _template, it's first argument will always be the key that it was added to.
var obj = {};
function addKey(key) {
obj[key] = _template.bind(null, key)
}
function _template(key, _params) {
console.log('Key is', key);
console.log('Params are',_params);
}
addKey('foo')
obj.foo({ some: 'data' }) // this will print "foo { some: 'data' }"
Reference - Function.prototype.bind()
try this Object.keys(this) and arguments.callee
var obj = {};
obj.test = function() {
var o = arguments.callee;
Object.values(this).map((a,b)=>{
if(a==o){
console.log(Object.keys(this)[b])
}
})
}
obj.one = "hi"
obj.test()
You can get the name of the method called with
arguments.callee.name
var a ={ runner_function : function(){ console.log(arguments.callee.name ); } };
a.runner_function() //It will return "runner_function"

Javascript + Angular + Prototype clear object properties

I am a bit confused, I would like to have a function that clears all the properties of an object which is available to all the instances of an object. So, I have added a prototype clear() function. This is the following code:
(function () {
Supplier.$inject = [];
angular.module('webclient').factory('Supplier', Supplier);
function Supplier() {
Supplier.prototype = {
clear: function () {
for (var key in this) {
//skip loop if the property is from prototype
if (this.hasOwnProperty(key))
continue;
console.log("key:" + key);
this[key] = undefined;
}
},
}
return Supplier;
};
})();
So, I would like to be able to clear all the properties of the current supplier object. So, if the supplier object had the following properties:
SupplierID:21,
Email:None
I would like to set the properties to undefined. I would use the class as following:
var supplier = new Supplier();
supplier.SupplierID = 21;
supplier.Email = "None";
And to set each property to undefined I would
supplier.clear();
Any ideas?
Thanks
try this: (plnkr)
function Supplier() {
var supplier = function() {};
supplier.prototype.clear = function() {
for (var key in this) {
if (!this.hasOwnProperty(key))
continue;
delete this[key];
}
};
return supplier;
}
hasOwnProperty return true if key is not in the prototype also prototype should be set outside of constructor, so your code should look like this:
function Supplier() { }
Supplier.prototype = {
clear: function () {
for (var key in this) {
if (this.hasOwnProperty(key)) {
console.log("key:" + key);
this[key] = undefined;
}
}
},
}
Don't set properties to undefined, just delete() them:
delete this[key];
And #jcubic is right, hasOwnProperty returns true if key is not in the prototype...

Which logger architecture in javascript? [duplicate]

Is there a way to make any function output a console.log statement when it's called by registering a global hook somewhere (that is, without modifying the actual function itself) or via some other means?
Here's a way to augment all functions in the global namespace with the function of your choice:
function augment(withFn) {
var name, fn;
for (name in window) {
fn = window[name];
if (typeof fn === 'function') {
window[name] = (function(name, fn) {
var args = arguments;
return function() {
withFn.apply(this, args);
return fn.apply(this, arguments);
}
})(name, fn);
}
}
}
augment(function(name, fn) {
console.log("calling " + name);
});
One down side is that no functions created after calling augment will have the additional behavior.
As to me, this looks like the most elegant solution:
(function() {
var call = Function.prototype.call;
Function.prototype.call = function() {
console.log(this, arguments); // Here you can do whatever actions you want
return call.apply(this, arguments);
};
}());
Proxy Method to log Function calls
There is a new way using Proxy to achieve this functionality in JS.
assume that we want to have a console.log whenever a function of a specific class is called:
class TestClass {
a() {
this.aa = 1;
}
b() {
this.bb = 1;
}
}
const foo = new TestClass()
foo.a() // nothing get logged
we can replace our class instantiation with a Proxy that overrides each property of this class. so:
class TestClass {
a() {
this.aa = 1;
}
b() {
this.bb = 1;
}
}
const logger = className => {
return new Proxy(new className(), {
get: function(target, name, receiver) {
if (!target.hasOwnProperty(name)) {
if (typeof target[name] === "function") {
console.log(
"Calling Method : ",
name,
"|| on : ",
target.constructor.name
);
}
return new Proxy(target[name], this);
}
return Reflect.get(target, name, receiver);
}
});
};
const instance = logger(TestClass)
instance.a() // output: "Calling Method : a || on : TestClass"
check that this actually works in Codepen
Remember that using Proxy gives you a lot more functionality than to just logging console names.
Also this method works in Node.js too.
If you want more targeted logging, the following code will log function calls for a particular object. You can even modify Object prototypes so that all new instances get logging too. I used Object.getOwnPropertyNames instead of for...in, so it works with ECMAScript 6 classes, which don't have enumerable methods.
function inject(obj, beforeFn) {
for (let propName of Object.getOwnPropertyNames(obj)) {
let prop = obj[propName];
if (Object.prototype.toString.call(prop) === '[object Function]') {
obj[propName] = (function(fnName) {
return function() {
beforeFn.call(this, fnName, arguments);
return prop.apply(this, arguments);
}
})(propName);
}
}
}
function logFnCall(name, args) {
let s = name + '(';
for (let i = 0; i < args.length; i++) {
if (i > 0)
s += ', ';
s += String(args[i]);
}
s += ')';
console.log(s);
}
inject(Foo.prototype, logFnCall);
Here's some Javascript which replaces adds console.log to every function in Javascript; Play with it on Regex101:
$re = "/function (.+)\\(.*\\)\\s*\\{/m";
$str = "function example(){}";
$subst = "$& console.log(\"$1()\");";
$result = preg_replace($re, $subst, $str);
It's a 'quick and dirty hack' but I find it useful for debugging. If you have a lot of functions, beware because this will add a lot of code. Also, the RegEx is simple and might not work for more complex function names/declaration.
You can actually attach your own function to console.log for everything that loads.
console.log = function(msg) {
// Add whatever you want here
alert(msg);
}

How to Monitor the Setting of new Properties on Javascript Objects

How could I get a callback whenever new properties are set on a Javascript Object..?
I.e. I don't know which properties are going to be set, but want a callback for any properties that are set.
What I want is
var obj = {};
obj.a = "something"; // triggers callback function
function callback(obj,key,val) {
console.log(key + " was set to " + val + " on ", obj);
}
Is this possible?
You can use the new defineProperty:
function onChange(propertyName, newValue){
...
}
var o = {};
Object.defineProperty(o, "propertyName", {
get: function() {return pValue; },
set: function(newValue) { onChange("propertyName",newValue); pValue = newValue;}});
But depends on the browser version you need to support.
Edit: Added snippet on Jsfiddle, works in IE10. http://jsfiddle.net/r2wbR/
The best thing to do it is a setter function, you don't need a getter,
var obj = {};
setKey(obj, 'a', "something"); // triggers callback function
function setKey(obj, key, val){
obj[key] = val;
callback(obj, key, val);
}
function callback(obj, key, val) {
console.log(key + " was set to " + val + " on ", obj);
}
Do it as generic as you can, don't do a different function for all keys
Try it here
The best idea is to have setter and getter methods. But according to your previous implementation one could still alter your object properties without using setter and getter. Therfore you should make you senstive variables privat. Here is a brief example:
var Person = (function() {
function Person() {};
var _name;
Person.prototype.setName = function(name) {
_name = name;
};
Person.prototype.getName = function() {
return _name;
};
return Person;
})();
var john = new Person();
john.getName();
// => undefined
john.setName("John");
john.getName();
// => "John"
john._name;
// => undefined
john._name = "NOT John";
john.getName();
// => "John"
Unfortunately, JavaScript won't let you know when a property is changed. Many times I've wished it would, but since it wouldn't I've had to find a workaround. Instead of setting the property directly, set it via a setter method which triggers the callback function (and possible use a getter method to access the property too) like this:
function callback(obj,key,val) {
console.log(key + " was set to " + val + " on ", obj);
}
var obj = {};
obj.setA=function(value){
obj.a=value;
callback(obj,'a',value);// triggers callback function
}
obj.getA=function(){
return obj.a;
}
obj.setA("something");
jsFiddle: http://jsfiddle.net/jdwire/v8sJt/
EDIT: Another option if you want to completely prevent changing the property without a callback:
function callback(obj,key,val) {
console.log(key + " was set to " + val + " on ", obj);
}
var obj={};
(function(){
var a=null;
obj.setA=function(value){
a=value;
callback(obj,'a',value);// triggers callback function
}
obj.getA=function(){
return a;
}
})()
console.log("a is "+obj.getA());// a is null
obj.setA("something"); // Set a to something
console.log("a is now "+obj.getA()); // a is now something
obj.a="something else"; // Set obj.a to something else to show how a is only accessible through setA
console.log("a is still "+obj.getA()); // a is still something
jsFiddle: http://jsfiddle.net/jdwire/wwaL2/

How to create class using object literal notation in javascript?

I want to create a class in Java Script. I can use basic functions coupled with prototypes but I want to use Object Literal Notation. Is is possible to create classes using Object Literal Notations?
You cannot create an instance of an object (and yes, you could even see functions as objects in Javascript, but I'm talking about literal defined objects), you must use a function to define a reusable class.
Cannot be done....well, depends on how you define the params of the requirements. Should be done? Up for debate.
The following is from an idea a coworker of mine had.
http://bit.ly/18xGdKi [JSBin with console example]
if (typeof (makeClass) === "undefined") {
makeClass = function(o) {
var F = function () {};
if (typeof (o) === "object" && o !== null) {
if (typeof (o.constructor) === "function") {
F = o.constructor;
}
F.prototype = o;
}
return F;
};
}
var MyClass = makeClass({
constructor: function (pName) {
var _myPrivateIdaho = 'Idaho ' + pName;
this.name = pName;
var _myPrivateFunc = function() {
console.log('You are in my ' +
_myPrivateIdaho +'.');
};
_myPrivateFunc();
},
getName: function() {
return this.name;
}
});
new MyClass('Bob');
new MyClass('Steve');

Categories