-1

I have a function in JavaScript:

function main() {
   console.log(this);
}

How come this logs Document? Surely it should log function main?

If not, then how do I declare a variable within main to be accessed by the rest of the code as main.varName?

Thank you!

Sean Bone
  • 3,368
  • 7
  • 31
  • 47

3 Answers3

1

Hey you can do something like this.

But then this would look something like a class object.

<script>

    function main() {
        this.testVar = "124";
    }

    var testMain = new main();

    alert(testMain.testVar);

</script>

The alternative is that you just create a normal global variable.

The way i am taking the code is a more class object way.

Hope i could help :)

Daniel
  • 2,002
  • 5
  • 20
  • 32
  • No, what i did is not wrong. You answer also lacks a reason. Please make more filling comments, your comment as it is right now is not constructive. – Daniel Dec 01 '13 at 18:52
0

The this keyword references the context of the function, not the function itself.

When you call a function as a method of an object, then this references the object, otherwise the context is the global context (document).

Example:

var o = {
  name: 'myObject',
  fn: function(){ alert(this.name); }
};

o.fn(); // alerts "myObject"

As a function is also an object, you can add properties to it:

function main() {
}

main.varName = 42;

alert(main.varName); // shows "42"

However, this is not a regular use of functions and objects. Normally main would be a plain object rather than a function if you want to access main.varName.

Guffa
  • 687,336
  • 108
  • 737
  • 1,005
0

Also, check out the module pattern

var person = function(){
   return module = {
      setName: function(name){
         module.name=name;
      }
   }
};

var bill = person();
bill.setName('bill');
console.log(bill.name);
actual_kangaroo
  • 5,971
  • 2
  • 31
  • 45