Navin Rauniyar
Navin Rauniyar

Reputation: 10535

why variable declared to function without new keyword is undefined?

function myFunc(){
    this.taste = 'yummi';
    console.log(this.taste);
    console.log(typeof this);//logs object
}
var noNewObj = myFunc();
console.log(typeof noNewObj);//logs undefined

within the myFunc the this keyword refers to new object that is noNewObj but outside the function the variable noNewObj is declared to be a function without new keyword which is not an object, why?

Upvotes: 2

Views: 62

Answers (3)

myFunc does not puts/returns anthing in noNewObj, so it is undefined

function myFunc(){
    this.taste = 'yummi';
    console.log(this.taste);
    console.log(typeof this);//logs object
    //return something here
}

Upvotes: 0

Bhojendra Rauniyar
Bhojendra Rauniyar

Reputation: 85575

No, it's wrong: within the myFunc the this keyword refers to new object that is noNewObj

If the new keyword is not used, then the 'this' variable inside the function will refer to the global object.

And there is no return value assigned so it logs undefined.

Upvotes: 0

GregL
GregL

Reputation: 38131

noNewObj is assigned the return value of calling myFunc(), which is undefined as no explicit return value is given.

If you were trying to use myFunc() as a constructor, you need to use the new keyword, like so:

var noNewObj = new myFunc();

Also, if you do mean to use myFunc() as a constructor, you should start it with a capital letter, as that is a common Javascript convention to indicate that a function is a meant to be invoked with new.

Upvotes: 3

Related Questions