0

Any ideas how the error is occuring? The class looks to be declared ok ..

car.js

function Car() {}

Car.prototype.setNumberOfWheels(numberOfWheels) {
    this.numberOfWheels = numberOfWheels;
}

Car.prototype.print() {
    console.log(this);
}

module.exports.Car = Car;

server.js

const model = require('./model.js');

Error:

Car.prototype.setNumberOfWheels(numberOfWheels) {
                                                ^

SyntaxError: Unexpected token {
    at createScript (vm.js:80:10)
    at Object.runInThisContext (vm.js:139:10)
    at Module._compile (module.js:617:28)
    at Object.Module._extensions..js (module.js:664:10)
    at Module.load (module.js:566:32)
    at tryModuleLoad (module.js:506:12)
    at Function.Module._load (module.js:498:3)
    at Module.require (module.js:597:17)
    at require (internal/module.js:11:18)
    at Object.<anonymous> (/Users/bob/git/project/server.js:2:15)
4
  • this.number of wheels, where are you calling the variable from? Nov 14, 2018 at 14:51
  • 4
    That's not the correct way to define a method. Nov 14, 2018 at 14:52
  • 2
    That line is in fact a syntax error. If you want to make that property a function, you have to do it in an assignment expression with a function instantiation expression on the right.
    – Pointy
    Nov 14, 2018 at 14:52
  • Yes, looking at @omri_saadon answer, I realise I missed ` = function()` when declaring the functions
    – bobbyrne01
    Nov 14, 2018 at 14:54

3 Answers 3

4

You should declare setNumberOfWheels and print as a functions.

Car.prototype.setNumberOfWheels = function(numberOfWheels) {
    this.numberOfWheels = numberOfWheels;
}

Car.prototype.print = function() {
    console.log(this);
}
1

The right way to declare a method using the shorthand syntax (on objects initializers) is:

var car = {}

Then to add methods,

Car.prototype.setNumberOfWheels = numberOfWheels => {
    this.numberOfWheels = numberOfWheels;
}

Car.prototype.print = () => {
    console.log(this);
}
1

In Ecmascript-5 you have to define setNumberOfWheels and print as functions ( see prototype examples )

function Car() {}

Car.prototype.setNumberOfWheels = function(numberOfWheels) {
    this.numberOfWheels = numberOfWheels;
}

Car.prototype.print= function() {
    console.log(this);
}

module.exports.Car = Car;

You can use ES6 Classes

class Car {
    setNumberOfWheels(numberOfWheels) {
        this.numberOfWheels = numberOfWheels;
    }
    print() {
        console.log(this);
    }
}


module.exports.Car = Car;
1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.