James Franco James Franco - 1 year ago 65
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 Source

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);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download