script.js:7 未捕获SyntaxError: Unexpected token { 问题排查求助
解决原型方法定义的语法错误
兄弟我太懂这种翻遍谷歌都找不到答案、自查N遍还没发现问题的抓狂感了!我仔细看了你的代码,终于找到那个藏起来的小细节:
你给Question原型添加displayQuestion方法的语法不对,正确的写法需要用赋值操作符把一个函数表达式绑定到原型属性上。
你的错误代码:
function Question(question, answers, correct){ this.question = question; this.answers = answers; this.correct = correct; } Question.prototype.displayQuestion(){ console.log(this.question); }
修正后的正确代码:
function Question(question, answers, correct){ this.question = question; this.answers = answers; this.correct = correct; } Question.prototype.displayQuestion = function(){ console.log(this.question); }
问题解释:
在JavaScript里,给构造函数的原型添加方法时,不能直接像声明普通函数那样写原型.方法名(){},必须用原型.方法名 = function(){}的形式,把匿名函数赋值给对应的原型属性。你之前的写法省略了= function这部分,导致语法解析错误,这就是引擎报错的根源。
内容的提问来源于stack exchange,提问作者Igor Marcos




