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

608 Views Asked by At

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() 
}
2

There are 2 best solutions below

2
On BEST ANSWER

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();

2
On

You can't use that syntax - you need to declare it like this:

x.prototype.y = function() {
    console.log("Hello");
};

This is because you're assigning an anonymous function to a property on an object - it's just like you'd do it in a constructor. Here's a full example of your code:

function x(a, b) {
  this.a = a
  this.b = b
}
x.prototype.y = function() {
  console.log("Hello");
};

var anX = new x("a", "b");
anX.y();