0

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();
1
  • 1
    Person is an object, not a class. Objects can only have properties. They don't have a concept of "local variables". Commented Apr 25, 2016 at 17:53

4 Answers 4

6

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">

Sign up to request clarification or add additional context in comments.

Comments

1

You could use a closure to simulate private properties.

function createPerson() {
  var name = 'Jake';

  return {
    printName: function() {
      return name;
    }
  };
}

var person = createPerson();
console.log(person.printName); // prints 'Jake'
console.log(person.name); // prints undefined
console.log(name) // throws 'Undefined variable' error

Comments

1

In case you want to use jQuery:

var Person = {
  name: "Jake",
  printName: function() {
    $("#personName").val(this.name);
  }
};
Person.printName();

https://jsfiddle.net/zmyLwtc0/2/

*val() is a jQuery method for the Element Object. In JS we use the attribute value instead.

Comments

1

You have a syntax error in how you wrote your code.

You've defined Person as an object while trying to use full JavaScript statements like var name = "jake";. Objects take key and value pairs. So the correct way to write the block is this:

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

Person.printName();

If you are looking to create a "class" of person, the alternate syntax you want to consider is:

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

var jake = new Person("Jake");

jake.printName();

Let me know if you have any questions!

2 Comments

.val(this.name); is jQuery.
Try .value = this.name;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.