What is the easiest way to get an object - is the prototype method now and later?

In JavaScript, if I have:

var foo = function(){} foo.prototype.bar = function() { console.log(this); } baz = new foo(); baz.name = 'baz'; bing = new foo(); bing.name = 'bing'; baz.bar(); bing.bar(); setTimeout(baz.bar); setTimeout(bing.bar); 

In my console, I see baz , bing , window , window objects in that order.

What will be the simplest or “normal” trickster to see:

baz , bing , baz , bing written using the variable "this-like" inside the function bar on the prototype foo ?

When I say "this-like", I mean a variable that I could use in bar() to access the object, that it is a method both now and later.

Edit:

For further clarification, I would like to avoid the need to know when I call bar () that he wants to use this , and so I will need to do something like bind() . Suppose that when I call bar() on baz or bing, this is a black box. I want to call bar () as a bing or baz method, not knowing how this works, and I want the insides of bar () to know what the method is.

+4
source share
3 answers

One strategy, if you prefer not to use bind() , is to bind your "related" methods to an object at build time, referring "indirectly" to this .

It:

 var foo = function(){ var _this = this; this.bar = function() { console.log(_this); } } baz = new foo(); baz.name = 'baz'; bing = new foo(); bing.name = 'bing'; baz.bar(); bing.bar(); setTimeout(baz.bar); setTimeout(bing.bar); 

Logs:

 baz bing baz bing 

But in general, I like to use this whenever possible, so I can apply() use my methods for other objects, if necessary. And I just encapsulate my “deferred calls” in anonymous functions under the assumption that they use this :

 setTimeout(function() { baz.bar(); }); setTimeout(function() { bing.bar(); }); 
+1
source

Use bind (although you may need to pin it for older browsers):

 setTimeout(baz.bar.bind(baz)); setTimeout(bing.bar.bind(bing)); // btw, // baz.bar.bind(bing) // foo.prototype.bar.bind(bing) // would have the same result 
+1
source

These days I do such things for convenience, without cheating, just a scope:

 function () { function _this() { return window.myObject; } window.myObject = { myMethod: function myMethod() { _this().myOtherMethod(); }, myOtherMethod: function myOtherMethod() { } } }(); 
0
source

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


All Articles