美文网首页
FCC高级编程篇之Make a Person

FCC高级编程篇之Make a Person

作者: 橙子_1259 | 来源:发表于2017-11-22 12:22 被阅读0次

    Make a Person

    Fill in the object constructor with the following methods below:

    getfirstname()
    getLastName()
    getFullName()
    setFirstName(first)
    setLastName(last)
    setFullName(firstAndLast)
    

    Run the tests to see the expected output for each method.
    The methods that take an argument must accept only one argument and it has to be a string.
    These methods must be the only available means of interacting with the object.

    考察闭包

    直接上代码好了

    let Person = function(firstAndLast) {
      let firstName, lastName;
    
      this.getFirstName = () => firstName;
    
      this.getLastName = () => lastName;
    
      this.getFullName = () => firstName + ' ' + lastName;
    
      this.setFirstName = first => firstName = first;
    
      this.setLastName = last => lastName = last;
    
      this.setFullName = firstAndLast => {
        firstAndLast = firstAndLast.split(' ');
        firstName = firstAndLast[0];
        lastName = firstAndLast[1];
      };
    
      this.setFullName(firstAndLast);
    };
    

    这里要注意的是this的使用。上述代码中,只有6个方法使用了this

    firstName, lastName不使用this是为了防止Person的实例直接访问。

    要真正实现私有属性,一种方式是使用闭包。即使这样做会增加资源占用。

    要想访问或设置firstName, lastName,必须使用给定的方法。

    下面是运行结果图。

    Make-a-Person.png

    相关文章

      网友评论

          本文标题:FCC高级编程篇之Make a Person

          本文链接:https://www.haomeiwen.com/subject/rlpnvxtx.html