Skip to main content
21. November 2021

Make an object

Objekte und Eigenschaften in einem simplen Beispiel umgesetzt.

const Person = function(firstAndLast) {

  String.prototype.splitter = function(divider, index) {
    return this.split(divider)[index]
  };

  let firstName = firstAndLast.splitter(" ", 0);
  let lastName = firstAndLast.splitter(" ", 1);
  let firstAndLastName = firstAndLast;

  this.setFirstName = function(first) {
    firstName = first;
    return this;
  };

  this.setLastName = function(last) {
    lastName = last;
    return this;
  };

  this.setFullName = function(firstAndLast) {
    firstName = firstAndLast.splitter(" ", 0);
    lastName = firstAndLast.splitter(" ", 1);
    return this;
  };

  this.getFirstName = function() {
    return firstName;
  };

  this.getLastName = function() {
    return lastName;
  };

  this.getFullName = function() {
    return firstName + " " + lastName;
  };

  return firstAndLastName;
};

const bob = new Person('Bob Ross');
bob.setFullName("Haskell Curry");
console.log(bob.getLastName());

No properties should be added. Object.keys(bob).length should always return 6.

bob instanceof Person should return true.

bob.firstName should return undefined.

bob.lastName should return undefined.

bob.getFirstName() should return the string Bob.

bob.getLastName() should return the string Ross.

bob.getFullName() should return the string Bob Ross.

bob.getFullName() should return the string Haskell Ross after bob.setFirstName("Haskell").

bob.getFullName() should return the string Haskell Curry after bob.setLastName("Curry").

bob.getFullName() should return the string Haskell Curry after bob.setFullName("Haskell Curry").

bob.getFirstName() should return the string Haskell after bob.setFullName("Haskell Curry").

bob.getLastName() should return the string Curry after bob.setFullName("Haskell Curry").

freeCodeCamp