JavaScript中的对象方法,带括号表示法

时间:2018-03-31 00:00:37

标签: javascript

var employee = {
  ["Last Name"]: "Smith",
  ["First Name"]: "Josh",
  ["Full Name"]: function() {
    return this["First Name"] + this["Last Name"]
  }
};
document.write("Good day" + this["Full Name"])

我目前正在学习JavaScript,我想使用括号表示法创建一个包含两个单词属性的对象,不幸的是,它给了我Good dayundefined而不是Good day Josh Smith的结果。我不知道我的代码应该是什么问题......

3 个答案:

答案 0 :(得分:3)

两个问题。

  1. 您需要使用this["First Name"],而不是(),因为您不在对象方法中。
  2. 您需要使用var employee = { ["Last Name"]: "Smith", ["First Name"]: "Josh", ["Full Name"]: function() { return this["First Name"] + this["Last Name"] } }; document.write("Good day" + employee["Full Name"]())
  3. 调用该函数

    [
     [[PointID_1, ImageSN_A, line, sample, goodness-of-fit],
      [PointID_1, ImageSN_B, line, sample, goodness-of-fit]]
     [[PointID_2, ImageSN_A, line, sample, goodness-of-fit],
      [PointID_2, ImageSN_B, line, sample, goodness-of-fit]]
    ]
    

答案 1 :(得分:2)

将“全名”转换为getter,并在调用时引用employee而不是此内容:

var employee = {
  "Last Name": "Smith",
  "First Name": "Josh",
  get "Full Name"() { // convert to getter
    return `${this["First Name"]} ${this["Last Name"]}`;
  }
};

document.write("Good day " + employee["Full Name"]) // refer to  employee instead of this

答案 2 :(得分:1)

var employee = { 
  "Last Name":"Smith", 
  "First Name":"Josh",
  "Full Name": function() {
    return  this["First Name"] +" "+ this["Last Name"];
  }
};
document.write("Good day " + employee["Full Name"]());