SitePoint Sponsor

User Tag List

Results 1 to 12 of 12
  1. #1
    SitePoint Enthusiast
    Join Date
    Mar 2013
    Posts
    79
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)

    question about the this keyword

    Code:
    function bar() {
            alert(this);
    }
    
    bar(); //global
    this outputs the following in an alert:
    [object]

    I'm reading about execution context and javascript and supposedly the above example is global execution context.

    What i want to know is why it prints out object?

    since this is global, i would think it would alert global.

    ________________


    Next example

    Code:
    var foo = {
    baz: function() { 
    alert(this);
    }
    
    }
    
    foo.baz();
    What this does, is it prints out an alert that says [object Object]

    my question is why is there a capital object along with a lowercase o object.

    I'm wondering what the object is. and why doesn't it print out foo since foo is the object. and when i run alert (this), it's being run inside the foo object.

    This is getting confusing for me.

  2. #2
    Programming Since 1978 silver trophybronze trophy felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, NSW, Australia
    Posts
    16,861
    Mentioned
    25 Post(s)
    Tagged
    1 Thread(s)
    The first one displays [object] because window is an object.

    The second one displays [object object] because both foo and baz are objects and this is pointing to foo.baz
    Stephen J Chapman

    javascriptexample.net, Book Reviews, follow me on Twitter
    HTML Help, CSS Help, JavaScript Help, PHP/mySQL Help, blog
    <input name="html5" type="text" required pattern="^$">

  3. #3
    Non-Member
    Join Date
    Feb 2012
    Posts
    892
    Mentioned
    10 Post(s)
    Tagged
    0 Thread(s)
    No, it doesn't alert "[object]", it alerts "[object Window]", for the first snippet. It only alerts [object] if you're using older IE versions. You shouldn't.

    It's the same with alert(this.toString()). The toString() method is called automatically whenever the object is referred in string like manner, which alert(this) does.

    The general description of toString() for objects is [object type]. In the first case, Window is the type of the global object: [object Window]. In the second case, Object is the type for the foo object: [object Object].

  4. #4
    SitePoint Enthusiast
    Join Date
    Mar 2013
    Posts
    79
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    Thanks, but my understanding of the this keyword is still kind of foggy.

    Is it basically just a reference to the active object?

  5. #5
    Patience... bronze trophy solidcodes's Avatar
    Join Date
    Jul 2006
    Location
    Philippines
    Posts
    936
    Mentioned
    3 Post(s)
    Tagged
    0 Thread(s)
    this - refers to the current object.

    HTH.
    Quality codes are optimized and tested...
    Click here for inspiration..

  6. #6
    Community Advisor bronze trophy
    fretburner's Avatar
    Join Date
    Apr 2013
    Location
    Brazil
    Posts
    1,433
    Mentioned
    45 Post(s)
    Tagged
    13 Thread(s)
    Inside global and anonymous functions, this is equal to the window object, or undefined when executing in strict mode.

  7. #7
    SitePoint Enthusiast
    Join Date
    Mar 2013
    Posts
    79
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)

    Question

    Code:
    <!DOCTYPE html><html lang="en"><body><script>
    var cody = {
      living:true,
      age:23,
      gender:'male',
      getGender:function(){return this.gender;}
    };
     
    console.log(cody.getGender()); // logs 'male'
     
    </script></body></html>
    I would like to know when this returns an object and when this will return a value from a property like in this example.

    Can someone show all the different variations of the way this is used?

  8. #8
    SitePoint Enthusiast
    Join Date
    Mar 2013
    Posts
    79
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by felgall View Post
    The first one displays [object] because window is an object.

    The second one displays [object object] because both foo and baz are objects and this is pointing to foo.baz
    is there any reason why the second Object is capitalized O? out of curiosity?

  9. #9
    SitePoint Enthusiast
    Join Date
    Mar 2013
    Posts
    79
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by fretburner View Post
    Inside global and anonymous functions, this is equal to the window object, or undefined when executing in strict mode.
    when you say strict mode,

    Code:
    // Whole-script strict mode syntax
    "use strict";
    var v = "Hi!  I'm a strict mode script!";
    any particular reasons why you're running in that mode?

  10. #10
    Community Advisor bronze trophy
    fretburner's Avatar
    Join Date
    Apr 2013
    Location
    Brazil
    Posts
    1,433
    Mentioned
    45 Post(s)
    Tagged
    13 Thread(s)
    Quote Originally Posted by wc43870n View Post
    when you say strict mode,

    Code:
    // Whole-script strict mode syntax
    "use strict";
    var v = "Hi!  I'm a strict mode script!";
    any particular reasons why you're running in that mode?
    As the name implies, it's more restrictive than the default mode, to prevent some kinds of errors by changing the way JS behaves. The explanation over at MDN is pretty good and goes into detail.

  11. #11
    Non-Member
    Join Date
    Feb 2012
    Posts
    892
    Mentioned
    10 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by wc43870n View Post
    Thanks, but my understanding of the this keyword is still kind of foggy.

    Is it basically just a reference to the active object?
    Short and sweet: http://www.infoworld.com/d/applicati...31322?page=0,1

    JavaScript secret No. 4: What's this?

    The this keyword is a huge stumbling block for many JavaScript developers to the point that some avoid it altogether. The best description of the topic I've seen so far was by Yehuda Katz in his blog post on function invocation. When not using call/apply or bind, the this value will always refer to the global object, except in the following instances:

    The function in question was called with the new operator, in which case this points to a new object being constructed.
    The function in question is a member of an object, in which case this points to the object.

    Rule 2 should be disregarded whenever the function involved is being called asynchronously, such as in a click handler or setTimeout. For example:
    Code:
    Person.getName(); // 'this' points to Person
    
    setTimeout(Person.getName, 1000); // 'this' points to the global object

    Quote Originally Posted by wc43870n View Post
    I would like to know when this returns an object and when this will return a value from a property like in this example.
    I'm not sure I get it right, I may be wrong, you're phrasing may be off too... to note, the this keyword will only work inside functions, and will only be used to reference an object, not a property. But you can use this to reference the object, and then use ".", like for any other named object, to look for a property of that object.

    Looking at your question, I believe you should take a step back and first get a better understanding of JavaScript objects, then worry about the this keyword. Everything in JavaScript is a property of an object, starting down from the global object.

  12. #12
    Programming Since 1978 silver trophybronze trophy felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, NSW, Australia
    Posts
    16,861
    Mentioned
    25 Post(s)
    Tagged
    1 Thread(s)
    Quote Originally Posted by fretburner View Post
    As the name implies, it's more restrictive than the default mode, to prevent some kinds of errors by changing the way JS behaves. The explanation over at MDN is pretty good and goes into detail.
    Rather than calling the other mode "default" mode I'd call it "old mode". All future versions of JavaScript will build on "strict mode" while retaining "old mode" simply so that antiquated scripts written for Netscape 4 do not break.

    Strict mode fixes some of the problems that JavaScript has due to it now being used for far more than was originally intended.

    As a simple example of something strict mode fixes is the requirement that everything be declared before use. This prevents the newbie error of accidental typos in variable names resulting in the script creating additional global variables instead of using the intended variable. Using old mode there is no easy way to tell why your 500 line JavaScript doesn't do what it is supposed to be doing. Using strict mode the script fails to run and the error console takes you straight to the typo.
    Stephen J Chapman

    javascriptexample.net, Book Reviews, follow me on Twitter
    HTML Help, CSS Help, JavaScript Help, PHP/mySQL Help, blog
    <input name="html5" type="text" required pattern="^$">


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •