简体   繁体   中英

Unexpected token 'this' while creating method inside object

I am creating an object and I continue to get the error message unexpected token:this when I add a method. Here's my code.

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.

I have read various articles about creating methods within objects and I don't see where I am going wrong here. When I remove the this. syntax from the name, age, gender, job variables in the method pSpeak, I get the error Unexpected identifyer .

Any suggestions as to whats happening?

You're missing a + when setting the 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.

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