我使用的是ES6和Angular2。在构造函数中声明某些内容之间有什么区别:
class Example{
constructor(private one: SomeClass, two: SomeClass){
this.two = two;
}
}
并且像这样:
class Example2{
private three:String = `What's the difference?`
}
到目前为止我理解如果我导入一个类,那么我有通过构造函数声明它。这里one
,two
和three
有什么区别?
答案 0 :(得分:1)
构造函数中的代码将在创建对象实例时执行。类中的代码,但构造函数外部变为类所使用的类字段/成员,或者可以在实例创建后调用。
在你的例子中。 $('#checkbox1').click(function() {
if ($(this).is(':checked')) {
$(document).on('click','[id^=element-]', function(e) {
console.log(this.id);
});
} else {}
});
和one
是在实例化类时预期传递给构造函数的参数的名称。必须将这些值传递给构造函数。
two
是一个“字段”。它由类创建,并在课程的生命周期中私下使用。它不会传入课堂。
所以,例如,用这个:
three
你会像这样实例化它:
class Example{
constructor(private one: SomeClass, two: SomeClass){
this.two = two;
}
}
但在这种情况下:
var someClass1 = new SomeClass();
var someClass2 = new SomeClass();
var myExample = new Example(someClass1, someClass2);
你只是实例化是这样的:
class Example2{
private three:String = `What's the difference?`
}
答案 1 :(得分:1)
class Example{
constructor(private one: SomeClass, two: SomeClass){
this.two = two;
}
}
是
的简写语法class Example{
private one: SomeClass;
constructor(one: SomeClass, two: SomeClass){
this.one = one;
this.two = two;
}
}
因此,如果在构造函数参数之前有private
,protected
或public
,则会通过一次传递给构造函数的值声明并初始化类字段。