SyntaxError:意外的令牌{尝试导出es5模块中的类以在另一个模块中使用时

时间:2018-11-14 14:49:15

标签: javascript ecmascript-5

任何想法错误是怎么发生的?该类似乎已声明为..

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

错误:

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)

3 个答案:

答案 0 :(得分:4)

您应该将setNumberOfWheelsprint声明为一个函数。

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

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

答案 1 :(得分:1)

使用shorthand syntax声明方法的正确方法(在对象初始化程序上)是:

var car = {}

然后添加方法

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

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

答案 2 :(得分:1)

在Ecmascript-5中,您必须将 setNumberOfWheels print 定义为函数(see prototype examples

function Car() {}

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

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

module.exports.Car = Car;

您可以使用ES6 Classes

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


module.exports.Car = Car;