Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.javascript > #29062

Scope of "this" variable

From Teemu Likonen <tlikonen@iki.fi>
Newsgroups comp.lang.javascript
Subject Scope of "this" variable
Date 2015-12-29 21:34 +0200
Organization A noiseless patient Spider
Message-ID <87ziwtqc9t.fsf@mithlond.arda> (permalink)

Show all headers | View raw


[Multipart message — attachments visible in raw view] - view raw

Code

    var Item = function() {
        this.variable = "variable";
        this.fn1 = function() { return this.variable; };
        this.foo = {
            fn2: function() { return this.variable; }
        };
    };

    var item1 = new Item();
    console.log(item1.fn1());
    console.log(item1.foo.fn2());

prints this:

    "variable"
    undefined

So function item1.fn1 returns the string "variable" but function
item1.foo.fn2 returns undefined. The variable "this" somehow disappears
(or doesn't last long enough) when a function object is created inside
another object {...}. Why?

I know a work-around:

    var Item = function() {
        this.variable = "variable";
        this.fn1 = function() { return this.variable; };
        var this_object = this;
        this.foo = {
            fn2: function() { return this_object.variable; }
        };
    };

But I'd like to understand why the first example works the way it does.
What's the difference between these to examples?

-- 
/// Teemu Likonen   - .-..   <https://github.com/tlikonen> //
// PGP: 4E10 55DC 84E9 DFF6 13D7 8557 719D 69D3 2453 9450 ///

Back to comp.lang.javascript | Previous | Next — Next in thread | Find similar | Unroll thread


Thread

Scope of "this" variable Teemu Likonen <tlikonen@iki.fi> - 2015-12-29 21:34 +0200
  Re: Scope of "this" variable Ben Bacarisse <ben.usenet@bsb.me.uk> - 2015-12-29 20:47 +0000
    Re: Scope of "this" variable Teemu Likonen <tlikonen@iki.fi> - 2015-12-30 10:57 +0200
  Re: Scope of "this" variable Thomas 'PointedEars' Lahn <PointedEars@web.de> - 2015-12-29 22:09 +0100
  Re: Scope of "this" variable Joao Rodrigues <groups_jr-1@yahoo.com.br> - 2015-12-29 19:38 -0200
    Re: Scope of "this" variable Joao Rodrigues <groups_jr-1@yahoo.com.br> - 2015-12-29 19:46 -0200
      Re: Scope of "this" variable Thomas 'PointedEars' Lahn <PointedEars@web.de> - 2015-12-30 00:42 +0100
    Re: Scope of "this" variable Thomas 'PointedEars' Lahn <PointedEars@web.de> - 2015-12-30 00:35 +0100
    Re: Scope of "this" variable Joao Rodrigues <groups_jr-1@yahoo.com.br> - 2015-12-30 02:18 -0200

csiph-web