Make a Person(FCC高级算法)

用下面给定的方法构造一个对象.

方法有 getFirstName(), getLastName(), getFullName(), setFirstName(first), setLastName(last), and setFullName(firstAndLast).

所有有参数的方法只接受一个字符串参数.

所有的方法只与实体对象交互.

 

没啥好说的,自己看看js   面向对象的资料

 

代码如下:

var Person = function(firstAndLast) {
    this.getFirstName = function(){
        return firstAndLast.split(" ")[0];
    }
    this.getLastName = function(){
      return firstAndLast.split(" ")[1];
    }
    this.getFullName = function(){
      return firstAndLast;
    }
    this.setFirstName = function(firstName){
        var regExp = new RegExp(""+firstAndLast.split(" ")[0]+"","g");  //创建一个正则对象匹配FirstName字符串
        firstAndLast = firstAndLast.replace(regExp,firstName);  // 用设置的firstName 替换掉firstAndLast 字符串中的  firstName字符串
    }
    this.setLastName = function(lastName){
        var regExp = new RegExp(""+firstAndLast.split(" ")[1]+"","g");
        firstAndLast = firstAndLast.replace(regExp,lastName);
    }
    this.setFullName = function(fullName){
        firstAndLast = fullName;
    }
};

 

posted on 2018-01-11 09:37  辣条菌的思维屋i  阅读(1077)  评论(0编辑  收藏  举报