A
A
AlphaDMQ2018-02-14 23:25:04
JavaScript
AlphaDMQ, 2018-02-14 23:25:04

When borrowing a method, does the object live or be sawn out?

...
arguments.join = [].join;
...

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Spirin, 2018-02-15
@AlphaDMQ

Firstly, you do not extend the method, but get a link to it. Secondly, the reference to the method, in your case, is not in the object itself, but is a property of the prototype. Third, in JavaScript , objects are deleted based on the reachability principle. If there is no reference to the object, then the memory occupied by it will be cleared as soon as possible. If there are references to the object, then this is not a guarantee that the memory will not be cleared.
For example:

let foo = {};
let bar = {};
foo.barLink = bar;
bar.fooLink = foo;

foo = bar = null;

The objects are referenced by barLink and fooLink , but they are unreachable because we can't access those properties after reassigning the variables foo and bar ,. Therefore, the memory occupied by objects will be cleared, despite the presence of references.
Your array will be destroyed by the garbage collector immediately after the execution of the line in which it is used.
Another thing is if we first bind the method to our object:
class Person {
  constructor(name) {
    this.name = name;
  }
  printName() {
    console.log(this.name);
  }
}

let john = new Person('John');
const obj = {};

obj.printJohnName = john.printName.bind(john);
john = null;

obj.printJohnName();  // 'John'

The object previously accessed by reference john will not be deleted, since we have bound a function on it and it has a hidden property that refers to it:
5a84af46ab784660788834.png

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question