Jake Jake - 7 months ago 14
Javascript Question

Define variables local to a JavaScript class

How do we define variables specific to the scope of JavaScript class?

In this fiddle below, I would like to define a variable called

name
specific to the class
Person
. I am getting an error
SyntaxError: missing : after property id


var Person = {
var name = "Jake";
printName: function()
{
document.getElementById("personName").val(this.name);
}
};

Person.printName();

Answer

You are creating Person wrongly and val() is not a javascript method. Try like following.

var Person = {
  name: "Jake",
  printName: function() {
    document.getElementById("personName").value = this.name;
  }
};

Person.printName();
<input type="text" id="personName">

Comments