繁体   English   中英

链式类方法抛出“不是函数”错误

[英]Chained class methods throw "not a function" error

我试图在 JS 类中做一个链接函数的练习。 我遇到了一些问题,其中函数的名称产生了一些奇怪的错误。

基本上,

const user = User.init();
user.name().first_name("Alice").last_name("Bob");

有功能

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;
}
}

产生一个错误,但是,

const user = User.init();
user.name().firstname("Alice").lastname("Bob");

有功能

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;
}
}

才不是。

错误信息

user.name().firstname("Alice").lastname("Bob");
        ^

TypeError: user.name(...).firstname is not a function

除了函数名称上的下划线外,这两种方法都是相同的。 有人在那里请告诉我什么是错误。 谢谢 !

您的User.init()调用new User() 这将创建一个新的User对象,其firstname是从类原型继承的,作为您的“设置名字”函数,然后通过设置this.firstname = ""迅速掩盖它。

在第二个示例中,您不执行this.first_name = "" ,并且对象保持功能。

通常,您应该决定哪些属性是方法,哪些属性是数据 - 不能同时使用一个属性。

(请注意,这也说明了适当上下文的重要性 - 从您第一次发布的代码片段中诊断出这一点的可能性几乎为零:))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM