代码之家  ›  专栏  ›  技术社区  ›  bobbyrne01

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

  •  0
  • bobbyrne01  · 技术社区  · 7 年前

    你知道错误是怎么发生的吗?该类看起来被声明为ok。。

    汽车.js

    function Car() {}
    
    Car.prototype.setNumberOfWheels(numberOfWheels) {
        this.numberOfWheels = numberOfWheels;
    }
    
    Car.prototype.print() {
        console.log(this);
    }
    
    module.exports.Car = Car;
    

    服务器.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 回复  |  直到 7 年前
        1
  •  4
  •   omri_saadon    7 年前

    你应该申报 setNumberOfWheels print 作为一个函数。

    Car.prototype.setNumberOfWheels = function(numberOfWheels) {
        this.numberOfWheels = numberOfWheels;
    }
    
    Car.prototype.print = function() {
        console.log(this);
    }
    
        2
  •  1
  •   Nelson Owalo    7 年前

    使用 shorthand syntax

    var car = {}
    

    然后添加方法,

    Car.prototype.setNumberOfWheels = numberOfWheels => {
        this.numberOfWheels = numberOfWheels;
    }
    
    Car.prototype.print = () => {
        console.log(this);
    }
    
        3
  •  1
  •   Vladu Ionut    7 年前

    在Ecmascript-5中,必须定义 和 打印 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;
    
    推荐文章