FCC高级编程篇之Make a Person

2017-11-22  本文已影响0人  橙子_1259

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
上一篇下一篇

猜你喜欢

热点阅读