[英]Chained class methods throw "not a function" error
I was trying to do an exercise for chaining function in JS classes.我试图在 JS 类中做一个链接函数的练习。 I ran into some issues where the name of the function is producing some weird error.
我遇到了一些问题,其中函数的名称产生了一些奇怪的错误。
Basically,基本上,
const user = User.init();
user.name().first_name("Alice").last_name("Bob");
with function有功能
class User
{
static init()
{
return new User();
}
constructor()
{
this.firstname = "";
this.lastname = "";
this.dob = "";
this.unit = "";
this.street = "";
this.suburb = "";
this.state = "";
this.postcode = "";
}
name()
{
console.log("lol this is name");
return this;
}
first_name(firstname)
{
console.log("Setting firstname");
return this;
}
last_name(lastname)
{
console.log("Setting lastname");
return this;
}
}
produces an error, however,产生一个错误,但是,
const user = User.init();
user.name().firstname("Alice").lastname("Bob");
with function有功能
class User
{
static init()
{
return new User();
}
constructor()
{
this.firstname = "";
this.lastname = "";
this.dob = "";
this.unit = "";
this.street = "";
this.suburb = "";
this.state = "";
this.postcode = "";
}
name()
{
console.log("lol this is name");
return this;
}
firstname(firstname)
{
console.log("Setting firstname");
return this;
}
lastname(lastname)
{
console.log("Setting lastname");
return this;
}
}
does not.才不是。
Error message错误信息
user.name().firstname("Alice").lastname("Bob");
^
TypeError: user.name(...).firstname is not a function
Both of these method is the same except for the underscore on the function name.除了函数名称上的下划线外,这两种方法都是相同的。 Is someone out there kindly tell me what is the error.
有人在那里请告诉我什么是错误。 Thanks !
谢谢 !
Your User.init()
calls new User()
.您的
User.init()
调用new User()
。 This will create a new User
object, whose firstname
is inherited from the class prototype as your "Setting firstname" function, and then promptly overshadow it by setting this.firstname = ""
.这将创建一个新的
User
对象,其firstname
是从类原型继承的,作为您的“设置名字”函数,然后通过设置this.firstname = ""
迅速掩盖它。
In the second example you don't do this.first_name = ""
, and the object remains functional.在第二个示例中,您不执行
this.first_name = ""
,并且对象保持功能。
In general, you should decide which properties are methods and which properties are data - you can't use one property for both.通常,您应该决定哪些属性是方法,哪些属性是数据 - 不能同时使用一个属性。
(Note that this also illustrates the importance of proper context - there was near-zero chance of diagnosing this from the code snippet you first posted :) ) (请注意,这也说明了适当上下文的重要性 - 从您第一次发布的代码片段中诊断出这一点的可能性几乎为零:))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.