简体   繁体   中英

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 eg this works:

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

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".

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

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.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM