简体   繁体   中英

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

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

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!

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM