javascript词法分析
大学有一门课程编译原理,记不太清楚了,大体意思是编译器在编译代码的时候,会首先对代码文件/文本进行分析,如果语法错根本就不会进行编译。
javascript run-time同样有这样的作用,没C++基础也没办法看V8源码,只是初探门径
前几天有个哥们问了下
1.toString() 和 1.1.toString()哪个能正常执行,我们先看看toString是怎么定义的,
reference: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object/toString
Returns a string representing the object.
Method of Object | |
---|---|
Implemented in | JavaScript 1.0 |
ECMAScript Edition | ECMAScript 1st Edition |
Syntax
object.toString()
Description
Every object has a toString()
method that is automatically called when the object is to be represented as a text value or when an object is referred to in a manner in which a string is expected. By default, the toString()
method is inherited by every object descended from Object
.
只有object才能调用toString, 我们使用 typeof 1 或是 typeof 1.1 得到的却是 number. 按上面的定义,这2句应该都执行不了。但是我们考虑
var h = ""; if(h) { // }
if是条件判断,里面需要传入boolean型,但是上面的代码编译无错。
我们得出一个结论
javascript run-time会将变量/对象在调用方法/添加行为时转为最恰当类型
回到前面的例子,当我们使用1.toString()会得到一句 [Chrome]SyntaxError: Unexpected token ILLEGAL, [Firefox]SyntaxError: identifier starts immediately after numeric literal
语法错误,而1.1.toString()能得到1.1
1.SoString就是词法分析时未通过,报出语法错误。
继续研究...