📜 ⬆️ ⬇️

Removing an object reference from a closure

var singleton = (function () { var data, method_args; data = []; method_args = []; function add (items) { var i; data.push(items); method_args.push(arguments); } function remove () { data.pop(); method_args.push(arguments); } return { add : add, remove : remove } }()); 

There is access to the singleton object.

Singleton's public methods (it is given as an example, and the value created by the closure created during its initialization) calls the array methods that one would like to get. In these methods, this refers to the desired array. So you can get to it through this .

If it were not for method_args.push , then it would be possible to get by redefining Array.prototype.push (with mandatory returning everything to its place after the object is “stolen”).
')
 var original_push, data; //    original_push = Array.prototype.push; //    Array.prototype.push = function () { //   data = this; }; //    singleton.add(); //      Array.prototype.push = original_push; //     console.log(data); 

However, push is used more than once. A single failure to comply with the method may lead to a breakdown. And this does not want. I want a link to the array. So rewrite the code above, while maintaining the standard logic of work. We create a new push method that is smart enough to take this reference only on the first call, and can mimic the default behavior.

 var original_push, fake_method_calls, data; //    original_push = Array.prototype.push; //  fake_method_calls = 0; //    Array.prototype.push = function () { //  this     if (fake_method_calls === 0) { data = this; } fake_method_calls += 1; //   return original_push.apply(this, arguments); } //    singleton.add(); //      Array.prototype.push = original_push; //     console.log(data); 

Voila: the sheep are intact (the standard logic is not broken) and the wolves are fed (reference in the hands).

Source: https://habr.com/ru/post/143288/


All Articles