Alice Xu
Alice Xu

Reputation: 543

Uncaught SyntaxError: Unexpected token ( error in Javascript

What's wrong with below code? Why I got an Uncaught SyntaxError: Unexpected token (

function Person(name){
    sayHi: function(){
      return "hi " + this.name;
    }
}

var john = new Person("John");
alert(john.sayhi());

Upvotes: 1

Views: 207

Answers (6)

ecarrizo
ecarrizo

Reputation: 2809

The problem is that declaration of sayHi is invalid because you are not in the same context as an object literal, so you are having a syntax error.

var o = { sayHi: function() {}} ;

you could do it using "this" (Because you are using "new" already) :

function Person(name){

    this.sayHi = function(){
        return "hi " + name;
    }
}

var john = new Person("John");
alert(john.sayHi());

another way is

function Person(name){

   return {
      sayHi : function() {
         return "hi " + name;
      }
   }
}    

var john = Person("John");
alert(john.sayHi());

Upvotes: 2

For additional clarity you can take the sayhi method out of the Person Object declaration as below.

Declare Person Object, including name and sayhi function.

function Person(nameString){
        this.name = nameString;
        this.message = sayhi;
    }

State what sayhi should do.

function sayhi(){
    return hiString = "hi " + this.name;
}

Initiate your Person

var john = new Person("John");

Call sayhi function on your Person Object and alert the return value

alert(john.sayhi());

Upvotes: 0

Bhavin Solanki
Bhavin Solanki

Reputation: 4818

Hi Please check this code

(function( $ ){
   $.fn.sayHi = function(name) {

      return name;
   }; 
})( jQuery );

alert($('body').sayHi('dasd'));

Upvotes: 0

Peter Peng
Peter Peng

Reputation: 1958

Using an Object Constructor:

function Person(name){
    this._name = name;
    this.sayHi = function(){
      return "hi " + this._name;
    }
}

var john = new Person("John");
alert(john.sayHi());

Upvotes: 0

takid1412
takid1412

Reputation: 356

You can change like this:

function Person(name){
    this.sayHi = function(){
      return "hi " + name;
    }
}

var john = new Person("John");
alert(john.sayHi());

Or something like this

function Person(name){
    this.name = name;
}
Person.prototype.sayHi = function(){
      return "hi " + this.name;
}
var john = new Person("John");
alert(john.sayHi());

Upvotes: 0

Mayank Saxena
Mayank Saxena

Reputation: 152

You should use this to make the variables and functions public of a class. If you dont use this keyword with variables then they can only accessible inside the class.

Please check this code.

function Person(name){
  this.sayHi = function(){
    return "hi " + name;
  }
}
var john = new Person("John");
alert(john.sayHi());

Upvotes: 1

Related Questions