James Franco
James Franco

Reputation: 4706

Why is the value of this variable undefined

I am currently learning javascript and came across this example

var t = function()
{
  this.name = "Jam";
  no = "123";
}

console.log(t.no); //Undefined 
var m = new t();
console.log(m.name);

Why is the first statement undefined ?

Upvotes: 2

Views: 197

Answers (4)

Charlie
Charlie

Reputation: 23778

t is a function expression. You you can access a returned object of a function like t().no or you can create a new object by using the function as a constructor like this

myT = new t()
console.log(t.no);

But your no variable is just a global variable inside the function and it is not a part of what it returns nor it is not attached to the returning object of the constructor function.

Here is a very good tutorial which covers all these topics at depths.

Upvotes: 1

Felix Kling
Felix Kling

Reputation: 816424

Why is the first statement undefined ?

Because t doesn't have a property no.

First of all, the code inside the function, namely

this.name = "Jam";
no = "123";

is only executed when the function is called. You are doing this with var m = new t();, which comes after console.log(t.no);.

Secondly, no = "123"; does not create a property on the function object. It will attempt to set the value of variable no. Since the variable doesn't exist in your example, that line will either create a global variable no, or throw in error if your code is in strict mode.

Consider the following example:

var no = 21;
function foo() {
  no = 42;
}
console.log(no); // 21
foo();
console.log(no); // 42

Upvotes: 2

Mattias Åslund
Mattias Åslund

Reputation: 3907

Because t is a function, that would be executed by t();. no on the other hand is a global scooed variable that is reached without prefix from everywhere.

Upvotes: 1

c-smile
c-smile

Reputation: 27460

t is a function object. As any other object, the function may have properties assigned. So in order your code to work you shall assign "123" to no property of your function (line A):

var t = function()
{
  this.name = "Jam";
}
t.no = "123"; // line A

console.log(t.no); // "123"
var m = new t();
console.log(m.name);

Upvotes: 5

Related Questions