为模拟信用卡申请发出简单的唯一ID

时间:2018-03-09 20:52:16

标签: javascript constructor global-variables counter default

我无法通过向我的creditUser类发出唯一ID来获取任何内容。我不确定我是否应该使用设置为0的全局变量或者我应该在构造函数中将其设置为0 ...或者在构造函数下面。我也不清楚如何定义余额(欠款)或者更确切地说,只是将其设置为0。我不知道应该在哪里宣布。任何和所有的帮助非常感谢!以下是repl.it- https://repl.it/@rockomatthews/Objects-Project

上的一个版本
//DO I SET THEM HERE?
var idCounter = 0;
var balance = 0;

    var CreditUser = class {

  constructor(
    id,
    firstName,
    lastName,
    income,
    limit,
    arp,
    balance
  ) {
      //OR DO I SET THEM HERE?
      this.id = id;
      this.firstName = firstName;
      this.lastName = lastName;
      this.income = income;
      this.limit = limit;
      this.balance = balance;
    }
};

//OR DO I SET THEM DOWN HERE SOMEWHERE TO 0?
var creditUser = new CreditUser (this.id, this.firstName, this.lastName, 
this.income, this.password);
  this.creditUser.id = this.id;
  this.creditUser.firstName = prompt("What's your first name?");
    console.log(this.creditUser.firstName);
  this.creditUser.lastName = prompt("What's your last name?");
    console.log(this.creditUser.lastName);
  this.creditUser.income = prompt("What's is your income this year?");
    console.log(this.creditUser.income);
  this.creditUser.limit = this.creditUser.income * .2;
  console.log(this.creditUser.limit);
    console.log(this.creditUser);

1 个答案:

答案 0 :(得分:1)

JavaScript提供了许多创建对象的方法......这是我熟悉的一种方式,使用函数作为对象,然后创建函数的新实例作为唯一对象。



// declare the parameters to be saved in the function
// declaration, so you can capture them in the object
var CreditUser = function( id, firstName, lastName, income, limit, balance ){
// use the OR statement to assign a default value
// to the parameters, if nothing is provided
  this.id        = id        || 0;
  this.firstName = firstName || '';
  this.lastName  = lastName  || '';
  this.income    = income    || 0;
  this.limit     = limit     || 0;
  this.balance   = balance   || 0;
};

// User a different variable name, to avoid 
// the object being overwritten or vice versa
var user1 = new CreditUser();
// change this. to the variable name of the new
// object.  'this' at this level means the document
    user1.firstName = prompt("What's your first name?");
    user1.lastName  = prompt("What's your last name?");
    user1.income    = prompt("What's is your income this year?");
    user1.limit     = user1.income * .2;

// user2 references the same object, but the data is
// separate from user1
var user2 = new CreditUser();
    user2.firstName = prompt("What's your first name?");
    user2.lastName  = prompt("What's your last name?");
  
// check the results of the user1 object vs. 
// the user2 object to prove they don't overwrite each
// other
console.log( user1 );
console.log( user2 );