如何在 cfscript 中重载 init() 函数
How to overload the init() function in cfscript
这个例子是我想要做的,但是 ColdFusion 说`routines can only declared once。 ColdFusion 可以做这样的事情吗?
/**
* @hint Handles vehicles
*/
component Vehicle
{
this.stock = "";
this.year = "";
this.make = "";
this.model = "";
public Vehicle function init()
{
return this;
}
public Vehicle function init(string stock)
{
this.stock = stock;
//Get the year, make model of the stock number of this vehicle
return this;
}
public string function getYearMakeModel()
{
var yearMakeModel = this.year & " " & this.make & this.model;
return yearMakeModel;
}
}
奇怪的是,如果我取出第一个 init()
,我可以使用 new Vehicle()
或 new Vehicle(stocknumber)
并且它会调用 init(string stocknumber)
但这不是我想要的行为...
ColdFusion 无法使用常规重载。但是单个函数可以使用不同的参数集 (required=false
)。这开辟了很多方法,您可以使用相同的功能来实现不同的目的。
例如,以下函数应该用于您尝试实现的两个构造函数。
public Vehicle function init(string stock=''){
if(len(trim(arguments.stock))){
this.stock = arguments.stock;
}
return this;
}
这个例子是我想要做的,但是 ColdFusion 说`routines can only declared once。 ColdFusion 可以做这样的事情吗?
/**
* @hint Handles vehicles
*/
component Vehicle
{
this.stock = "";
this.year = "";
this.make = "";
this.model = "";
public Vehicle function init()
{
return this;
}
public Vehicle function init(string stock)
{
this.stock = stock;
//Get the year, make model of the stock number of this vehicle
return this;
}
public string function getYearMakeModel()
{
var yearMakeModel = this.year & " " & this.make & this.model;
return yearMakeModel;
}
}
奇怪的是,如果我取出第一个 init()
,我可以使用 new Vehicle()
或 new Vehicle(stocknumber)
并且它会调用 init(string stocknumber)
但这不是我想要的行为...
ColdFusion 无法使用常规重载。但是单个函数可以使用不同的参数集 (required=false
)。这开辟了很多方法,您可以使用相同的功能来实现不同的目的。
例如,以下函数应该用于您尝试实现的两个构造函数。
public Vehicle function init(string stock=''){
if(len(trim(arguments.stock))){
this.stock = arguments.stock;
}
return this;
}