Angular 2+变量提升?
Angular 2+ variable hoisting?
Angular 如何解析它的所有变量,而不管它们放置在组件中的什么位置?
例如在 Vanilla JS 中
console.log(a) // undefined
let a = 'Hello;
Angular 分量
ngOnInit(){
this.example()
}
example(){
console.log(this.a) // Hello
}
a = 'Hello'
我知道这是不好的做法,编译器会抱怨变量的放置,但是 none 我对 Angular 是如何做到这一点的,或者它是否不是一个很好奇Angular具体行为?
这不是 Angular 行为。实际上,您提供的这段代码在 class 中,而 a
不是变量,实际上它是 属性.
JavaScript(和 Typescript)不需要在方法(构造函数)之前声明属性,因为它只是一个声明,将来会在 class 实例化时使用。
虽然 tslint
可能会警告您将其放置在方法之后,但这只是编码风格问题。
您可以将 class 转换为传统的函数构造函数:
class Car {
make = 'default';
drive() {
/* ... */
}
model = 'foo'
}
可以写成(并在 browsers that doesn't support ES6 Class 上使用一些 polyfill 时转换为):
var Car = function() {
this.make = 'default';
this.model = 'foo';
}
Car.prototype.drive = function() {
/* ... */
}
请注意,在第二种情况下,属性是在构造函数中定义的,因此它总是 运行 在调用方法之前。
Angular 如何解析它的所有变量,而不管它们放置在组件中的什么位置?
例如在 Vanilla JS 中
console.log(a) // undefined
let a = 'Hello;
Angular 分量
ngOnInit(){
this.example()
}
example(){
console.log(this.a) // Hello
}
a = 'Hello'
我知道这是不好的做法,编译器会抱怨变量的放置,但是 none 我对 Angular 是如何做到这一点的,或者它是否不是一个很好奇Angular具体行为?
这不是 Angular 行为。实际上,您提供的这段代码在 class 中,而 a
不是变量,实际上它是 属性.
JavaScript(和 Typescript)不需要在方法(构造函数)之前声明属性,因为它只是一个声明,将来会在 class 实例化时使用。
虽然 tslint
可能会警告您将其放置在方法之后,但这只是编码风格问题。
您可以将 class 转换为传统的函数构造函数:
class Car {
make = 'default';
drive() {
/* ... */
}
model = 'foo'
}
可以写成(并在 browsers that doesn't support ES6 Class 上使用一些 polyfill 时转换为):
var Car = function() {
this.make = 'default';
this.model = 'foo';
}
Car.prototype.drive = function() {
/* ... */
}
请注意,在第二种情况下,属性是在构造函数中定义的,因此它总是 运行 在调用方法之前。