The 'this' keyword always refers to the object on which the method is defined, but instead may vary depending on specific contexts. How?

I looked at this article http://dev.opera.com/articles/view/objects-in-javascript/ where I read "'this', the keyword always refers to the object on which the method is defined, but can change instead depending on specific contexts. " I could not find a single example in which 'this' does not refer to an object by the method .... please give an example if possible

+4
source share
6 answers

There are many ways to change the context. jsfiddle

using bind: (not supported by older IE browsers (IE <9))

var obj = {}; function fun1(){}; obj2 = {}; obj2.fun1 = fun1.bind(obj); obj2.fun1(); // context inside fun1 would be obj. 

Using an application or call.

 var obj = {}; function fun1(){}; obj2 = {}; obj2.fun1 = function(){ fun1.apply(obj, arguments); //or fun1.call(obj, ar1, arg2,...); }; obj2.fun1(); // context inside fun1 would be obj. 
+2
source

One example that you could really accomplish and not expect this result:

 var obj = { testFunc : function(){ alert("testFunc: " + this); } } obj.testFunc(); // this is the object setTimeout(obj.testFunc, 1000); // this is window 

http://jsfiddle.net/t7ycd/

+3
source

Here is one way

 var a = {}; a.foo = function(){ console.log(this); } a.foo(); // object a a.foo.call(window); // window object 
+1
source

If you call a method in class B from class A, 'this' will refer to the class that calls the method - A, not the class in which it is located.

0
source

Here is an example taken directly from the Mozilla documentation

https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/this

 var o = {prop: 37}; function independent() { return this.prop; } of = independent; console.log(of()); // logs 37 

Thus, the independent function is defined in the global context, but then bound to the object. When it is called on this object, the context becomes the object on which the function is called, and not the object on which the function is defined.

You can achieve similar results using javascript call and bind methods and use anonymous functions.

0
source

like this

 var MyObject = function() { this.initialize(); } MyObject.prototype.SomeMethod = function() { //common fix is to use //var self = this; (function(){ //this has lost scope //self will retain the this scope that was desired })(); } 
0
source

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


All Articles