The code is:

var func = function(){
this.a(){
     //here 'this' refers to 'func'
};
var b = function(){
    //here 'this' refers to 'window'
};
};

This is kind of beginner question, but are there any simple rules that I can follow to determine what context I'm currently in?

Thanks in adv.

The value of `this' depends on the context in which the function was invoked and hence can only be known at runtime. Hence saying that "here `this' refers to XXX" holds little truth since I can very well have a object with its property set to func.a in which case the `this' will refer to the object in consideration rather than `func'.

A sample script [untested]:

<!--
`this' in ECMAscript

Copyright (C) 2008  sos aka Sanjay

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
-->
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
  <head>
    <meta http-equiv="Script-Content-Type" content="text/javascript">
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Example</title>
    <script type="text/javascript">
      function func() {
        return "In func() with this=" + this.name;
      }

      function A() {
        this.a = func;
        this.name = "A";
      }

      function B() {
        this.b = func;
        this.name = "B";
      }

      window.onload = function() {
        window.name = "WINDOW";
        var invokeA = new A().a();
        var invokeB = new B().b();
        var invokeW = func();
        var invokeSeq = "Invocation sequence: <br>--> new A().a()<br>" +
          "--> new B().b()<br>--> func()<br><br>";

        var elem = document.getElementById("results");
        elem.innerHTML =
          invokeSeq + invokeA + "<br>" + invokeB + "<br>" + invokeW;
      }
    </script>
  </head>
  <body id="bdy">
    <div id="results"></div>
  </body>
</html>
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.