任何想法错误是怎么发生的?该类似乎已声明为..
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)
答案 0 :(得分:4)
您应该将setNumberOfWheels
和print
声明为一个函数。
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;