JavaScript - Object Oriented Programming

在此直接附上習題:

第一題:

  1. Create a constructor function for a Person. Each person should have a firstName, lastName, favoriteColor, favoriteNumber.
  1. Add a function on the Person.prototype called fullName that returns the firstName and lastName property of an object created by the Person constructor concatenated together.

    • Examples:

      1
      2
      var person = new Person('Elie', 'Schoppik', 'purple', 34);
      person.fullName(); // 'Elie Schoppik'
  2. Add a property on the object created from the Person function called family which is an empty array. This will involve you going back and adding an additional line of code to your Person constructor you previously created in exercise 1.

  3. Add a function on the Person.prototype called addToFamily which adds an object constructed from the Person constructor to the family array. To make sure that the object you are adding is an object construced from the Person constructor (HINT - take a look at the instanceof keyword). Make sure that your family array does not include duplicates! This method should return the length of the family array.

    • Examples:

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      var person = new Person('Elie', 'Schoppik', 'purple', 34);
      var anotherPerson = new Person();
      person.addToFamily(anotherPerson); // 1
      person.addToFamily(anotherPerson); // 1
      person.family.length; // 1

      person.addToFamily('test'); // 1
      person.addToFamily({}); // 1
      person.addToFamily([]); // 1
      person.addToFamily(false); // 1
      person.family.length // 1
    • Solution:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
function Person(firstName, lastName, favoriteColor, favoriteNumber) {
this.firstName = firstName;
this.lastName = lastName;
this.favoriteColor = favoriteColor;
this.favoriteNumber = favoriteNumber;
this.family = [];
}

Person.prototype.fullName = () => this.firstName + ' ' + this.lastName;
Person.prototype.addToFamily = person => {
if (this.family.indexOf(person) === -1 && person instanceof Person) {
this.family.push(person);
}
return this.family.length;
}

Array.prototype.map = callback => {
var newArr = [];
for (var i = 0; i < this.length; i++) {
newArr.push(callback(this[i], i, this));
}
return newArr;
}

String.prototype.reverse = () => {
var newStr = '';
for (var i = this.length - 1; i >= 0; i--) {
newStr += this[i];
}
return newStr;
}

第二題:

  1. Implement your own version of Array.prototype.map. The function should accept a callback and return a new array with the result of the callback for each value in the array.

  2. Implement a function called reverse that reverses a string and place it on the String.prototype.

    • Examples:

      1
      2
      'test'.reverse();       // 'tset'
      'tacocat'.reverse(); // 'tacocat'