Javascript语法糖:class

描述:

通过以下属性定义一个Person类:

  1. 包含四个参数的constructor:firstName(默认”John”),lastName(默认“Doe”),age(默认0),gender(默认“Male”)。
  2. sayFullName方法,不含参数,返回FullName,如“John Doe”。
  3. greetExtraTerrestrials静态方法,包含一个参数raceName,返回”Welcome to Planet Earth raceName”,如:raceName为“Martians”,则返回”Welcome to Planet Earth Martians”。

MyCode:

class Person {
  // Get coding in ES6 :D
  constructor(firstName="John",lastName="Doe",age=0,gender="Male")
  {
    this.firstName = firstName;
    this.lastName = lastName;
    this.age = age;
    this.gender = gender;
  }
  sayFullName()
  {
    return this.firstName + " " + this.lastName;
  }

  static greetExtraTerrestrials(raceName)
  {
    return "Welcome to Planet Earth " + raceName;
  }
}

CodeWar:

class Person {
  constructor(firstName = 'John', lastName = 'Doe', age = 0, gender = 'Male') {
    Object.assign(this, { firstName, lastName, age, gender });
  }
  sayFullName() {
    return `${this.firstName} ${this.lastName}`;
  }
  static greetExtraTerrestrials(raceName) {
    return `Welcome to Planet Earth ${raceName}`;
  }
}

你可能感兴趣的:(白色八阶,Javascript)