Skip to content Skip to sidebar Skip to footer

How To Refer Itself In A Function Regardless Of Extenal Variable Changes?

I have a function which has other functions defined: var A = function(n) { console.log(n + A.num()); } A.num = function() { return 5; } I want to change the name to B and dele

Solution 1:

You can always refer to the current function using its explicit name (if it has one).

So, change the definition, to name the function, and refer to it using that:

var A = function currentFunction(n) {
  console.log(n + currentFunction.num());
}
A.num = function() {
  return 5;
}

var B = A;
A = undefined;
B(10); //15

console.log(typeof currentFunction) //undefined, function name is local

Note: the abovementioned approach won't work if the function is named implicitly, but will continue to work if the function is renamed via fn.name


Alternatively, if the function isn't an arrow function, you can also use arguments.callee, that will work even with anonymous functions, but its use isn't recommended:

var A = function (n) {
  console.log(n + arguments.callee.num());
}
A.num = function() {
  return 5;
}

var B = A;
A = undefined;
B(10); //15

Unfortunately, none of the above will work with arrow functions, if you want to refer to itself, use a named bound function expression instead.


Solution 2:

actually that's normal, because in js you can't really copy object

// Define object bar
var bar = {
   x : 'Hi'
}
console.log(bar.x);  //Hi

// Assign it to foo
var foo = bar;
console.log(foo.x);  //Hi

//But
foo.x = 'Hello!! Im foo.';
console.log(foo.x);  //Hello!! Im foo.
console.log(bar.x);  //Hello!! Im foo.

bar.x = "Nice to meet you foo!!";
console.log(foo.x);  //Nice to meet you foo!!
console.log(bar.x);  //Nice to meet you foo!!

you have to return a new one with the same value as the last

var foo = {...bar};

and this is not working because B is always calling 'num' from A that doesn't exist, One way to sever the parity would be stringify the initial function, then use a function constructor to create the clone after replacing the 'A' by 'B' but tell me more why are you facing this problem ?


Solution 3:

var A = function(n) {
  if(!this.num){
  console.log("This is not available coz obj is not created");
  console.log("Below error is for testing purpose");
  }
  let a=this.num(n);
  console.log(a);
}
//use prototype here 
//A.num = function() {
A.prototype.num=function(n){
  return n+5;
}
//use new to create object 
new A(5);
var B = A;
A = undefined;
//use new to create object 
new B(6);

B(5);//lets try without using new keyword
.as-console-wrapper { max-height: 100% !important; top: 0; }

Post a Comment for "How To Refer Itself In A Function Regardless Of Extenal Variable Changes?"