Make a Person

題目:
  用Object-Oriented 來設計6個函數來取得姓名與全名: 1. getFirstName(), 2. getLastName(), 3.getFullName(), 4. setFirstName(first), 5. setLastName(last), and 6. setFullName(firstAndLast)
var Person = function(firstAndLast) {
    var fullName = firstAndLast;

    this.getFullName = function()
    {
      return fullName;
    };

    this.getFirstName = function()
    {
      return fullName.split(" ")[0];
    };

    this.getLastName = function()
    {
        return fullName.split(" ")[1];
    };

    this.setFullName = function(firstAndLast)
    {
        fullName = firstAndLast;
    };

    this.setFirstName = function(first)
    {
        fullName = first + " " + fullName.split(" ")[1] ;
    };

    this.setLastName = function(last)
    {

        fullName = fullName.split(" ")[0] + " " + last ;
    };

};


var bob = new Person('Bob Ross');
bob.getFullName();

測試的正確結果

Object.keys(bob).length 应该返回 6.
bob instanceof Person 应该返回 true.
bob.firstName 应该返回 undefined.
bob.lastName 应该返回 undefined.
bob.getFirstName() 应该返回 "Bob".
bob.getLastName() 应该返回 "Ross".
bob.getFullName() 应该返回 "Bob Ross".
bob.getFullName() 应该返回 "Haskell Ross" after bob.setFirstName("Haskell").
bob.getFullName() 应该返回 "Haskell Curry" after bob.setLastName("Curry").
bob.getFullName() 应该返回 "Haskell Curry" 在 bob.setFullName("Haskell Curry") 之后.
bob.getFirstName() 应该返回 "Haskell" 在 bob.setFullName("Haskell Curry") 之后.
bob.getLastName() 应该返回 "Curry" 在 bob.setFullName("Haskell Curry") 之后.

Solution:

  使用下面定義函數
this.methodName = function(args)
{
//do something
};
用function建立Object物件時,this是指被這個建構子/構造函數(Constructor-Using for initialization)創造出來的Object,而在裡面寫this.wheels = 4或this.property,這邊的property就是新的Object裡面帶有的屬性
var Car = function() {
  this.wheels = 4;
  this.engines = 1;
  this.seats = 1;
};
//wheels、engines、seats都是car的屬性

```



**P.S. / Reference:  Details of the Object Model
           Closures
           Challenge Construct JavaScript Objects with Functions

results matching ""

    No results matching ""