sapna koramagiri
sapna koramagiri

Reputation: 81

Why accessing property on a function object gives undefined?

The function object Foo when accessing it property x using this operator gives undefined. Why ?

function Foo(){ 
        this.x = "bar";
        return this;
    }

console.log(Foo.x); //undefined

I believe declaring a function JS automatically creates a function object to which you can add properties. For e.g this works:

Foo.today = "Sunday";
console.log(Foo.today); // Sunday

Upvotes: 0

Views: 64

Answers (4)

Ivan Markitan
Ivan Markitan

Reputation: 21

Calling Foo.x will return 'undefined' as x is an instance(object) property not a function property(Foo.x = "bar"). Declare x as a class(function) property Foo.x = "bar"; than call it in console.log(Foo.x).

In this case x is an instance property (this.x ='bar') not a class(function) property(as Foo.x='bar') to get access to Foo.x,Foo has to be instantiated "var foo = new Foo()" than calling foo.x is returning Foo's instance property of x.

Upvotes: 0

wiredolphin
wiredolphin

Reputation: 1641

Speaking on non "strict" mode, in the context you used it, this keywords defaults to the global object since it is not yet set by a call to the function itself. So you simply set a x property on the window Object.

Upvotes: 0

Kingmaker
Kingmaker

Reputation: 519

Just delete return this; and use var f = new Foo(). Then console.log(f.x) will work.

Upvotes: 0

Pointy
Pointy

Reputation: 414086

Functions are objects. You're adding an "x" property to whatever this refers to when the function Foo() is called, but nothing in your code calls it.

If you were to call the function like this:

Foo.call(Foo);

before checking the value of Foo.x, it would work. Generally, however, the value of this in a function call is not a reference to the function itself.

You can also do:

Foo.x = "bar";

Usually, assigning properties to this in a function, especially one used as a constructor, is done to manage properties of objects (objects that are not the function itself). So:

var f = new Foo();

will give you an object with a property named "x" and value "bar".

Upvotes: 1

Related Questions