Link to "this" inside setInterval / setTimeout in object prototype methods

I usually assign an alternate reference to "self" when I refer to "this" inside setInterval. Is it possible to do something similar in the context of a prototype? The following code errors.

function Foo() {} Foo.prototype = { bar: function () { this.baz(); }, baz: function () { this.draw(); requestAnimFrame(this.baz); } }; 
+24
source share
2 answers

Unlike a language such as Python, the Javascript method forgets that it is a method after retrieving it and passing it elsewhere. You can either

Wrap a method call inside an anonymous function

Thus, access to the baz property and its call occurs at the same time, which is necessary for correctly setting this inside the method call.

You will need to store this from the external function in a helper variable, since the internal function will refer to another this object.

 var that = this; setInterval(function(){ return that.baz(); }, 1000); 

Wrap a method call inside the thick arrow function

In Javascript implementations that implement the arrow function of a function , you can write the above solution in a more concise way using the fat arrow syntax:

 setInterval( () => this.baz(), 1000 ); 

Fat arrow's anonymous functions save this from the surrounding function, so there is no need to use the var that = this trick. To find out if you can use this function, refer to the compatibility table, for example this one .

Use the snap function

The ultimate alternative is to use a function like Function.prototype.bind or the equivalent from your favorite JavaScript library.

 setInterval( this.baz.bind(this), 1000 ); //dojo toolkit example: setInterval( dojo.hitch(this, 'baz'), 100); 
+52
source

i made a proxy class :)

 function callback_proxy(obj, obj_method_name) { instance_id = callback_proxy.instance_id++; callback_proxy.instances[instance_id] = obj; return eval('fn = function() { callback_proxy.instances['+instance_id+'].'+obj_method_name+'(); }'); } callback_proxy.instance_id = 0; callback_proxy.instances = new Array(); function Timer(left_time) { this.left_time = left_time; //second this.timer_id; this.update = function() { this.left_time -= 1; if( this.left_time<=0 ) { alert('fin!'); clearInterval(this.timer_id); return; } } this.timer_id = setInterval(callback_proxy(this, 'update'), 1000); } new Timer(10); 
0
source

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


All Articles