javascriptobjectprototypeobject-constructionfunction-constructor

Function Constructor - add function using prototype gives - Uncaught SyntaxError: Unexpected token {


I tried adding a function y() into the object constructor x using prototype chaining. It results to an unexpected error:

Unexpected token {

function x(a, b) {
  this.a = a
  this.b = b
}
x.prototype.y(){
  console.log('hello')
}

I want the function x as:

function x(a, b) {
  this.a = a; 
  this.b = b; 

  y() 
}

Solution

  • You're not assigning y to a function. Your syntax is invalid. Instead, use an anonymous function:

    x.prototype.y = function() {...}

    See working example below:

    function x(a, b) {
      this.a = a
      this.b = b
    }
    
    x.prototype.y = function() {
      console.log('hello');
    }
    
    let a = new x(1, 2);
    a.y();

    If you wish for the method to be static you can omit the prototype:

    function x(a, b) {
      this.a = a
      this.b = b
    }
    
    x.y = function() {
      console.log('hello');
    }
    
    x.y();