SyntaxError

SyntaxError 对象代表尝试解析语法上不合法的代码的错误。

描述

当Javascript语言解析代码时,Javascript引擎发现了不符合语法规范的tokens或token顺序时抛出SyntaxError.

语法

new SyntaxError([message[, fileName[, lineNumber]]])

参数

message
可选的. 可阅读的错误描述信息
fileName
可选的. 包含引发异常的代码的文件名
lineNumber
可选的. 包含引发异常的代码的行号

属性

SyntaxError.prototype (en-US)
允许SyntaxError对象添加属性.

方法

全局 SyntaxError 自身不包含任何方法, 但从原型链中继承了一些方法.

SyntaxError 实例

属性

{{page('/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/SyntaxError/prototype', '属性')}}

方法

{{page('/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/SyntaxError/prototype', '方法')}}

示例

捕获 SyntaxError

try {
  eval('hoo bar');
} catch (e) {
  console.log(e instanceof SyntaxError); // true
  console.log(e.message);                // "missing ; before statement"
  console.log(e.name);                   // "SyntaxError"
  console.log(e.fileName);               // "Scratchpad/1"
  console.log(e.lineNumber);             // 1
  console.log(e.columnNumber);           // 4
  console.log(e.stack);                  // "@Scratchpad/1:2:3\n"
}

创建 SyntaxError

try {
  throw new SyntaxError('Hello', 'someFile.js', 10);
} catch (e) {
  console.log(e instanceof SyntaxError); // true
  console.log(e.message);                // "Hello"
  console.log(e.name);                   // "SyntaxError"
  console.log(e.fileName);               // "someFile.js"
  console.log(e.lineNumber);             // 10
  console.log(e.columnNumber);           // 0
  console.log(e.stack);                  // "@Scratchpad/2:11:9\n"
}

规范

Specification Status Comment
ECMAScript 3rd Edition (ECMA-262) Standard Initial definition.
ECMAScript 5.1 (ECMA-262)
SyntaxError
Standard  
ECMAScript 2015 (6th Edition, ECMA-262)
SyntaxError
Standard  

浏览器兼容性

We're converting our compatibility data into a machine-readable JSON format. This compatibility table still uses the old format, because we haven't yet converted the data it contains. Find out how you can help! (en-US)
Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari
Basic support (Yes) (Yes) (Yes) (Yes) (Yes)
Feature Android Chrome for Android Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
Basic support (Yes) (Yes) (Yes) (Yes) (Yes) (Yes)

相关链接