这个 JavaScript 很好用,因为 JS 运行时在运行语句之前解析所有的声明。
try {
function Test() {
this.speak = function() { alert('From Test!') }
}
test = new Test
test.speak()
} catch (error) {
alert(error);
}
try {
secondtest = new SecondTest
secondtest.speak()
function SecondTest() {
this.speak = function() { alert('From SecondTest!') }
}
} catch (error) {
alert(error)
}
// Alert: 'From Test!'
// Alert: 'From SecondTest!'
但是,当我在其声明之上创建一个类的实例时,相应的 CoffeeScript 不起作用:
try
class Test
speak: -> alert 'From Test!'
test = new Test
test.speak()
catch error
alert error
try
secondtest = new SecondTest
secondtest.speak()
class SecondTest
speak: -> alert 'From SecondTest!'
catch error
alert error
// Alert: 'From Test!'
// Alert: 'TypeError: undefined is not a function'