Is javascript a global object?

Does the "this" value correspond to the global object or the "o" object in the program below?

More importantly, what code could I run to verify that the link is "this"?

function F() { function C() { return this; } return C(); } var o = new F(); 
+4
source share
3 answers

It refers to a global object ( window ).

Edit: in fact, it will refer to both: the global object and o , because they are the same. o will refer to the object returned from F() , which is the object returned from C() , which is the window object;)

You can call console.log(this) to find out which object it belongs to. It should provide you with a list of all the object methods in the console, and you should be able to infer from that object. For this to work in Firefox, you need Firebug. I don’t know IE.

Update:

@Anurag has already shown you how to explicitly set this . If you just want to refer to this higher scope, you need to explicitly assign it to a variable. Example:

 function F() { var that = this; function C() { console.log(that); } C(); } 
+12
source

this refers to the global object in your program. To get this link to instance F try

 function F() { function C() { return this; } return C.call(this); // call C with the object of F as a context } var o = new F(); 

In Chrome, you can simply enter a variable to check, and its value will be logged. This is similar to executing console.log(object) , but much easier to work with. Here is a screenshot of the launch of this sample code in Chrome. The value of the last o statement is automatically printed, and I printed it again to be sure. He registered a DOMWindow that references the global window object in the browser.

enter image description here

+2
source

To add to other answers:

When a function is called, this set depending on how it is called. If it is called using myfunc.call or myfunc.apply , then this set to the first argument passed. If it is called in "dotted" form, that is, myObject.myfunc() , then this set to everything that is before the point.

There is an exception to this rule that allows you to bake this in with bind , in which case it will be all that was connected. that is, in var boundfunc = myfunc.bind(myobj); then boundfunc is called any time, it will be like calling myfunc , but with this , referring to myobj , regardless of anything else. Here is an example that does this:

 function F() { var C = function() { return this; }.bind(this); return C(); } var o = new F(); 

If none of these cases apply, then this always either a global object ( window if you are in a browser), or if you are in strict mode, it is undefined .

0
source

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


All Articles