简体   繁体   English

在JavaScript类中定义局部变量

[英]Define variables local to a JavaScript class

How do we define variables specific to the scope of JavaScript class? 我们如何定义特定于JavaScript类范围的变量?

In this fiddle below, I would like to define a variable called name specific to the class Person . 在下面的这个小提琴中,我想定义一个名为name的变量,该变量特定于Person类。 I am getting an error SyntaxError: missing : after property id 我收到错误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. 您错误地创建了Person并且val()不是JavaScript方法。 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"; 您已在尝试使用完整的JavaScript语句(例如var name = "jake";Person定义为对象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: 如果您想使用jQuery:

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

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

* val() is a jQuery method for the Element Object. * val()是Element对象的jQuery方法。 In JS we use the attribute value instead. 在JS中,我们改用属性value

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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