繁体   English   中英

具有构造函数init的Javascript类

[英]Javascript Classes with constructor init

我正在尝试使具有属性和功能的模块可以像验证器对象一样使用,该对象可以验证内部的所有对象,并带有一个有效的方法,如果验证器成功,该方法将返回true。

所以我做这个文件

function Machine(params)
{
    // this is the constructor
    if(params){
        var pub=params;
        return this.init(pub);
    }
    this.obj_params = 'null';
    this.valid = 'Not Valid';
};
Publicacion.prototype.init = function(objConfig){
    console.info('Init Success!')
    this.buildMachine(objConfig);

    return true
};
Publicacion.prototype.buildPublish = function(objConfig){
    console.info('Builded!');
    //this.valid='success'; // when uncommited, the object this.valid appears

    return true;
};

module.exports=Machine;

这是控制台

> var Machine=require('./Machine')
> undefined
> var machinegun=new Machine();
> Init Success!
> Builded!
> undefined
> machinegun.valid
> undefined

两个问题:

  1. 当我尝试访问“ machinegun.valid”时,这返回了一个未定义的信息
  2. 当我使用build方法定义有效时,将显示var valid。

为什么构造函数最初没有定义有效变量? 为什么有效的变量可以通过build方法定义?

我不明白javascript如何与类一起使用...

谢谢!

该函数可以设置this.valid之前返回this.init(pub) 您应该首先在构造函数中定义this.valid

您正在跳过另一个。 逻辑是,如果传递了参数,请使用它们进行初始化,否则设置两个“ no params”属性:

function Machine(params)
{
    // this is the constructor
    if(params){
        var pub=params;
        return this.init(pub);
    }
    else {
      this.obj_params = 'null';
      this.valid = 'Not Valid';
    }
};

嗯,首先

Publicacion.prototype.

应该是

Machine.prototype

和Publicacion.prototype.buildPublish

应该

Machine.buildMachine

但这可能不是你的意思。

有效为您返回false的简单原因是您没有定义它-在此之前从函数返回。

只需更改顺序:

function Machine(params)

this.obj_params = 'null';
this.valid = 'Not Valid';
{
    // this is the constructor
    if(params){
        var pub=params;
        return this.init(pub);
}

};

暂无
暂无

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

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