The This in JavaScript

Source: Internet
Author: User

He scope of all functions are window .

(The reason is invoking as a and not f function(类,全局的类) a method .) When invoked as a function are set to during the execution of the this window target)

To circumvent that, you can do this:

A.prototype.go = function () {    var = this;    Console.log (self); A {go=function ()}    var f = function () {         console.log (self);  A {go=function ()}               };    f ();}

  thisWould only does refer to the window while it is in the method of a class and not just a regular function. –

Take a look at some interesting code and guess what the This variable pops up.

function Menu (elem) {alert (this);  function Privatemethod () {alert (this)  //window, not menu!  }  ... call private method  Privatemethod ()}new Menu (document.createelement (' div '))

  

Because function is not f() called without any object reference. Try,

f.apply(this);
function Menu (elem) {alert (this);  function Privatemethod () {alert (this)  //window, not menu!  }  ... call private method  privatemethod.apply (this)}new Menu (document.createelement (' div '))

——------------------------------------------------------------------------------------------------------------- --------------

Reference Stack-overflow:

Http://stackoverflow.com/questions/9674252/javascript-why-this-inside-the-private-function-refers-to-the-global-scope

Http://javascript.info/tutorial/binding

JavaScript has a different concept of what the special name this refers to than most other programming languages do. There is exactly five different ways in which the value of this can is bound in the language.

The Global Scope
this;

When using this in global scope, it would simply refer to the global object.

Calling a Function
foo();

Here, would this again refer to the global object.

ES5 Note: In strict mode, the global case no longer exists. Would instead has the value of in the this undefined .

Calling a Method
test.foo();

In this example, would this refer to test .

Calling a Constructor
new foo();

A function call, which is preceded by the new keyword acts as a constructor. Inside the function, would this refer to a newly created Object .

Explicit Setting of this
functionFoo(A,B,C) {}VarBar= {}; foo. (bar, [ 1, 2 3);  //array would expand to the Belowfoo.call (bar, 1, 2 3//results in a = 1, b = 2, c = 3            

When using call the or apply methods Function.prototype of, the value of this inside the called function gets explicitly set To the first argument of the corresponding function call.

As a result, in the above example the method case does not apply, and inside of'll be this foo set To bar .

Note: this cannot is used to refer to the object inside of a Object literal. var obj = {me: this}so won't result me obj in referring to, since only gets bound by one of the this five listed Cases.

Common Pitfalls

While most of these cases make sense, the first one are to be considered another mis-design of the language because it Never have any practical use.

  foo. Method = function ()  Span class= "pun" >{ function Test ()  { // This was set to the global object   } Test (); }             /span>            

A common misconception this test Foo is the inside of refers to;

In order to gain access Foo to from within test , it's necessary to create a local variable inside of method which refer S to Foo .

  foo. Method = function ()  Span class= "pun" >{ var that =  this;function Test ()  { //use it instead of this here }  Test ();                /span>                

thatis just a normal variable name, but it's commonly used for the reference to an outer this . In combination with closures, it can also is used to pass this values around.

assigning Methods

Another thing that does does work in JavaScript are function aliasing, which is assigning a method to a VA Riable.

var test = someObject.methodTest;test();

Due to the first case, now test acts like a plain function call; therefore, this inside it'll no longer refer someObject to .

While the late binding of might seem like a bad idea at first this , in fact, it's what makes Prototypal inheritance work .

function Foo() {}foo.. Method = function ()  Span class= "pun" >{}; function bar ()  {}bar.= foo.; new bar ().               

When method gets called on a instance Bar of, would now refer to that this very instance.

Disclaimer: Shamelessy stolen from my own resources at http://bonsaiden.github.com/JavaScript-Garden/#function.

The This in JavaScript

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.