James Franco James Franco - 6 months ago 8
Javascript Question

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 ?

Answer

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);
Comments