Understand the JavaScript keyword this

2009-07-01  来源:本站原创  分类:AJAX  人气:525 

Original: Understanding JavaScript's this keyword

A few days ago, I wrote an article on aspects of the JavaScript-oriented article on how to use the wrapper to replace the given function or method. To fully understand this concept, the correct understanding of JavaScript to their keyword "this" of the treatment is helpful. JavaScript how to determine the context of a wide range of what this means, this article gives a brief summary.

Let us start with the beginning of the following examples of Bob:

var Bob = {
  name: "Bob",
  greet: function() {
    alert( "Hi, my name is " + this.name );
  }
};

Here, we have created a member of the Object have two examples of a simple character name, and one that contains references to the name of the method greet, when the implementation of Bob.greet () method, greet () function with Bob as this the object. Now, let us take a look at the same Bob.greet () object in the new implementation will be how to:

var Alice = {
  name: "Alice",
  greet: Bob.greet
};

Consider the following, which one is the Alice.greet () the output of this?

1.  "Hi, my name is Bob", or
   2. "Hi, my name is Alice" 

If you choose the "2", right! Bob function greet the "this.name" until the function of the real implementation will be resolved, so that when Alice.greet () is called, function greet () of this is set to Alice. However, if the function call itself, rather than as an object's methods, what can happen? Take a look at the following:

var unboundGreet = Bob.greet;
unboundGreet();

Predictive functional you unboundGreet () will output what? The answer is "" Hi, my name is ". This is because when a non-binding when the function is called," this "object is set to the overall window, and there is no definition of window.name, so have a space character.

The following examples you will see the hidden debug will not bind a headache:

setTimeout( Bob.greet, 1000 ); // Call Bob.greet 1 second from now

Developers may wish to Bob.greet () call in the second after, it's bound to the Bob will output "Hi, my name is Bob", but this is expected and does not appear, on the contrary, the greet () method only can be referred to as non-binding, with its output unboundGreet () is the same. Equivalent to the following code might be able to more clearly explain the reasons:

var unboundGreet = Bob.greet;
setTimeout( unboundGreet, 1000 );

Here, it is clear that in the implementation of time (one second after), the function greet () is a non-binding. When you approach an object as an event processor, the same will occur. Take a look at the following HTML:

<a href="">Greetings!</a>

Add the following JavaScript:

document.getElementById("clickme").onclick = Bob.greet;

Might we expect this will trigger link output "Hi, my name is Bob", but click on it, and call the results of unboundGreet () is the same.
To resolve the issue of implied non-binding way is to create a function, use it to package without the scope of the method (the bound method). JavaScript library includes the majority of such assistants, most of the time Function.prototype by adding a method to complete the bind.
Not in this way here, following a simple example of how this wrapper Jiancang (wrapper).

var bobsGreet = function() {
  Bob.greet();
};

setTimeout( bobsGreet, 1000 );

Or, more simply,

setTimeout( function(){

  Bob.greet();

}, 1000 );

This is the full content of this article.

相关文章
  • Understand the JavaScript keyword this 2009-07-01

    Original: Understanding JavaScript's this keyword A few days ago, I wrote an article on aspects of the JavaScript-oriented article on how to use the wrapper to replace the given function or method. To fully understand this concept, the correct unders

  • export of the javascript keyword 2011-05-19

    Today, my colleagues used to do the export as the export js function name, has been reported missing '(', I read the code did not spread the problem, no way, can only comment the code troubleshooting and tried many times and found as long as the expo

  • common set of javascript keyword list (keywords and future keywords) 2010-11-01

    Javascript Keywords (Reserved Words) is in the Javascript language has a specific meaning and become part of the syntax Javascript those words. Javascript tags are not as variable and function names used. Use Javascript keywords as variable or functi

  • Understand the JavaScript function (the difference between functions and objects and links) 2010-11-29

    Function objects and other internal object relations In addition to the function object, there are many internal objects, such as: Object, Array, Date, RegExp, Math, Error. These names actually represent a type of new operator can return an object. H

  • The use of JavaScript document.cookie summary 2010-08-27

    "Some Web sites on your hard disk in very small text file stored some information on these documents is called Cookie." - MSIE help. In general, Cookies are CGI or similar advanced than HTML documents, procedures created, but javascript Cookies

  • JavaScript Type Conversion 2010-09-27

    As a dynamic language, JavaScript's type conversion is always carried out in silence, not many people know. However, understanding the type of conversion is a good understanding of JavaScript JavaScript in the basic course. The conversion mechanism i

  • JavaScript how to systematically study 2010-11-12

    In the past, JavaScript is used to do some simple web effects, such as form validation, floating ads, etc. So then JavaScript is not taken seriously. Since the AJAX became popular, people found that using JavaScript can give users a better experience

  • JavaScript learning process and experience 2011-01-10

    Transfer from: http://www.cnblogs.com/webflash/archive/2010/08/14/1799668.html I. Introduction In the past, JavaScript is used to do some simple web effects, such as form validation, floating ads, etc. So then JavaScript is not taken seriously. Since

  • JavaScript (1) 2009-03-24

    Original: Lee warfare (leadzen). Shenzhen 2008-2-23 Programming the world exist only two basic elements, one is data, a code. Programming world is in the data and code in a web of tangled displays unlimited vigor and vitality. Data is inherently quie

  • Wu first javascript 2009-04-11

    http://www.cnblogs.com/leadzen/archive/2008/02/25/1073404.html Classic Introduction Programming the world exist only two basic elements, one is data, a code. Programming world is in the data and code in a web of tangled displays unlimited vigor and v

  • (Private Lee war blog)JavaScript 2009-08-21

    Introduction Programming world there are two basic elements of only one data, one is the code. Programming data and the world is entangled in a web of code displays unlimited vigor and vitality. Data is inherently quiet, and always want to maintain t

  • The understanding of the JavaScript object prototype 2009-10-18

    Article Transfer from: http://www.iebe.cn/blog/article.asp?id=93 JS a lot of people who are hard to understand learning JavaScript is a prototype of what the Dongdong, the following text to follow me, let me lead you solve the mystery of the prototyp

  • JavaScript Study Notes 2009-09-03

    1, JavaScript does not support multidimensional arrays, except as arrays of arrays. 2, JavaScript is an untyped language, the elements of an array do not all need to be of the same type, as they do in typed languages like Java. 3, Arrays can be creat

  • JavaScript object-based programming concepts (Ext) 4 2010-03-23

    With regard to avoid namespace pollution problems, Ext provides a special namespace function, you can define a new namespace, the following example: <script type="text/javascript"> / / Ext Namespaces / / For example, we want to give our ow

  • JavaScript object-based programming concepts (Ext) 5 2009-10-26

    <script type="text/javascript"> / / Understand the javascript in this var obj1 = ( prop1: "obj1: World, Hello", hello: function () ( alert ( "obj1 alert:" + this.prop1); ) ); var obj2 = ( prop1: "obj2: World, Hello

  • JavaScript event bubbling demo 2008-12-23

    Reproduced: If you do not understand the JavaScript event bubbling down to see: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http:/

  • Get to know the synchronized keyword in java 2010-04-01

    In fact, I on the basics of java more than 90% are from Thinking in Java. For one of the synchronized keyword, then that is a look, probably know the meaning, and no scan. Later, the keyword has not been used. Yesterday to see Thinking in Patterns wi

  • javascript cross-domain set the cookie (2 domain) 2010-05-08

    <script language="javascript" type="text/javascript"> function setCookie(c_name,value,expiredays) { var exdate=new Date(); exdate.setDate(exdate.getDate()+expiredays); document.cookie=c_name+"="+escape(value)+((expireda

  • javascript technology base 1 (reprint) 2010-10-14

    javascript object-oriented technology infrastructure (a) Seen a lot of object-oriented technology introduced javascript article, it is faint. Why? Not because of poorly written, but because of too deep. No javascript object in going to explain how on

  • About this keyword in the thinking JS 2010-10-31

    I am in the process of learning JavaScript keyword this took me a lot of energy, but also take a lot of detours, with reference to many previous articles, and now the usage of this keyword are summarized below: First look at the following code: funct