【问题标题】:Unexpected token 'this' while creating method inside object在对象内创建方法时出现意外的标记“this”
【发布时间】:2014-10-19 01:20:04
【问题描述】:

我正在创建一个对象,当我添加一个方法时,我继续收到错误消息 unexpected token:this。这是我的代码。

function Person(name,age,gender,job) {
    this.name = name,
    this.age = age,
    this.gender = gender,
    this.job = job,
    this.pSpeak = function() { 
        func.innerHTML = "My name is " + this.name + "<br>I am " this.age + "years old." + "<br>I am a " + this.gender + ".<br>My career is " + this.job +".";
        } //Object Method
    }

 var colin = new Person("Colin James",24,"man","Social Media Consultant"); // create a new Person.

我已经阅读了有关在对象中创建方法的各种文章,但我看不出我在哪里出错了。当我从 pSpeak 方法中的 name、age、gender、job 变量中删除 this. 语法时,我收到错误 Unexpected identifierer

对发生的事情有什么建议吗?

【问题讨论】:

  • 你在字符串"&lt;br&gt;I am " this.age 中错过了+ 应该是"&lt;br&gt;I am " + this.age
  • @monkeyinsight 谢谢!就是这样。我不敢相信我错过了!
  • 老实说,我确实一遍又一遍地阅读它,但我一直错过它。

标签: javascript object methods this


【解决方案1】:

您在设置innerHTML 时缺少+

function Person(name,age,gender,job) {
    this.name = name,
    this.age = age,
    this.gender = gender,
    this.job = job,
    this.pSpeak = function() { 
        func.innerHTML = "My name is " + this.name + "<br>I am " + this.age + "years old." + "<br>I am a " + this.gender + ".<br>My career is " + this.job +".";
        } //Object Method
    }

 var colin = new Person("Colin James",24,"man","Social Media Consultant"); // create a new Person.

【讨论】:

    猜你喜欢
    • 2021-02-20
    • 1970-01-01
    • 1970-01-01
    • 2016-06-11
    • 2023-03-11
    • 2016-09-08
    • 2017-04-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多