FCC高级编程篇之Make a Person

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,必须使用给定的方法。

下面是运行结果图。

测试结果图

转载于:https://www.cnblogs.com/laoho/p/7878577.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值