class Point {
public x: any;
public y: any
constructor(x: any, y: any) {
this.x = x;
this.y = y
}
}
let point = new Point(1, 2);
console.log(point.x)
class Point {
constructor(public x: any, public y: any) { }
}
let point = new Point(1, 2);
console.log(point.x)
第一种写法我能理解,可是第二种是什么意思呢,在constructor的参数里加上public就不用在类里面声明属性了吗?就不用写public x: any;和this.x = x;了???
这里面是什么原理呢?
这是typescript语法,第一种和第二种写法是等价的,或者说第二种写法是第一种写法的简化。参数加上private或者public,会自动加上一个类的属性和参数同名,然后在构造器中给这个类属性赋值,是个语法糖。