-1

In this console:

Console Image

When B is set to A but A was destroyed afterwards, B.b() throws an error because A is truly undefined.

How can one avoid this?

PS: I am aware that I can simply return this (or change the function in some way) but that doesn't fulfill my purposes.

EDIT: How do I 'localise' and somehow tell javascript that by A, I mean B even if A is undefined, WITHOUT ALTERING THE FUNCTION ITSELF?

Angshu31
  • 1,172
  • 1
  • 8
  • 19
  • 2
    Could you elaborate your purposes in the question, seeing as `this` keyword is used for precisely that? – Anurag Srivastava Mar 26 '20 at 18:21
  • Images are fine, but text is better. Imagine if you couldn't see the image; your text wouldn't make sense. Please include either just text, or both. – Heretic Monkey Mar 26 '20 at 18:22
  • `return this.a` should work – Barmar Mar 26 '20 at 18:23
  • You could also just change `B.b` to look at `B` instead of `A`. I.e., `B.b = function () { return B.a; };`. But @Anurag's question is a good one; why not avail yourself of the obvious and purpose-built mechanism for this functionality? – Heretic Monkey Mar 26 '20 at 18:30
  • @HereticMonkey,I don't want to change the function. – Angshu31 Mar 26 '20 at 20:37
  • @HereticMonkey and everyone else, Can you check [this](https://stackoverflow.com/questions/60876579/how-to-clone-a-function-but-handle-the-variables-too) out? Thanks. – Angshu31 Mar 26 '20 at 21:46

3 Answers3

0

You should change your A to look like the following:

let A = {
  a: "a",
  b: function() {
    // change A.a to this.a
    return this.a;
  }
};

Right now since it references A when you destroy A Even though B is already equal to A the b method still needs the original A to exist. Swapping it for this will fix the issue.

mikerojas
  • 2,238
  • 1
  • 4
  • 7
  • Thanks, for your contribution, can you check [this](https://stackoverflow.com/questions/60876579/how-to-clone-a-function-but-handle-the-variables-too) out as well? Thanks. – Angshu31 Mar 26 '20 at 21:45
0

The way the question and example is written that "error" cannot be avoided. return A.a; will and SHOULD be undefined based on your example because you are assigning A = undefined;

Also, if you are trying to clone an object, there are a couple of other options you should look into like:

  1. let B = JSON.parse(JSON.stringify(A));
  2. let B = Object.assign({}, A); MDN
  3. Javascript classes

And maybe check out this answer: How do I correctly clone a JavaScript object?

Jason Lydon
  • 7,074
  • 1
  • 35
  • 43
0

To the new viewers, if you want to do this without altering the function:

var A = (function() {
  var A = {a: 90, b: function() { return A.a }}; // same object as in the Q
  return A;
})()

console.log(A.b()) // 90

var B = A;
A = undefined;

console.log(B.b()) // Also 90

B.a = 89;
console.log(B.b()) // 89
Angshu31
  • 1,172
  • 1
  • 8
  • 19