使用多个参数集创建相同的JavaScript对象

时间:2018-02-10 14:59:57

标签: javascript

我想初始化一个javascript对象Person。

class Person {
    constructor(name) {
        this.hash = hash(name);
        this.name = name;
    }
    toString() {
        return this.name + " hashValue: " + this.hash;
    }
}

hash(string)是一个返回hash值的现有函数。

当网页加载时,我将li附加到网页上的ul,其中包含Person对象的内容。因此,每次重新加载网页时,我都需要创建人物对象的客户端。

用户还可以创建新的人员。创建新人时,必须计算新的hashValue。但是当从数据库中检索现有人员时,已经存在hashValue。在这种情况下,我不想计算hashValue。

我想用:

创建一个Person对象
const pers1 = new Person(name); // user adds new Person

const pers2 = new Person(hash, name); // Person from database

这可能吗?

2 个答案:

答案 0 :(得分:0)

是的,可能

  • 必须调用该函数与hash不同,以避免发生逻辑冲突。

询问传递的哈希参数:

this.hash = hash ? hash : hashthis(name);

<强>段:

这只是演示逻辑

的一个例子

&#13;
&#13;
function hashthis(str) {
  return `Hash(${str})`;
}
  
class Person {
  constructor(name, hash) {
    this.hash = hash ? hash : hashthis(name);
    this.name = name;
  }   
  
  toString() {
    return this.name + " hashValue: " + this.hash;
  }
}

console.log(new Person('Ele'));
console.log(new Person('Ele', 'dhgf65df6df7'));
&#13;
&#13;
&#13;

或者您可以使用函数hashthis使用默认值初始化您的参数。仅当散列参数未定义/未传递时,才会发生此初始化。

constructor(name, hash = hashthis(name))

<强>段

&#13;
&#13;
function hashthis(str) {
  return `Hash(${str})`;
}

class Person {
  constructor(name, hash = hashthis(name)) {
    this.hash = hash;
    this.name = name;
  }

  toString() {
    return this.name + " hashValue: " + this.hash;
  }
}

console.log(new Person('Ele'));
console.log(new Person('Ele', 'dhgf65df6df7'));
&#13;
&#13;
&#13;

答案 1 :(得分:0)

如果你愿意,你可以做的一件事是区分第一次创建人的过程和恢复已经创建的人的过程。

例如:

function yourHashFunction(text) {
 //your hash function code
}

class Person {
    constructor(name, hash) {
        this.name = name;
        this.hash = hash ? hash : yourHashFunction(name);
    }

    static fromDatabase(name, hash) {
        return new Person(name, hash);
    }

    toString() {
        return this.name + " hashValue: " + this.hash;
    }
}

const pers1 = new Person('Gijs'); // user adds new Person

const pers2 = Person.fromDatabase('Gijs', '2f23f67'); // Person from database

使用数据库中的静态函数(或您喜欢的名称)可以帮助您识别第一次创建人员的地点(可能在某些情况下可能需要,或者甚至可能需要用于跟踪目的)收回已经创建的人。