为了账号安全,请及时绑定邮箱和手机立即绑定

用于虚拟人的getter\setter

用于虚拟人的getter\setter

www说 2019-07-04 15:26:38
用于虚拟人的getter\setter我一直在试着让自己的头脑清醒过来,但它并没有沉入其中。我读过JavaScript getter和Setters和定义getter和Setters只是不明白而已。有人能清楚地说:一个能手和策划者应该做什么,而且给出一些非常简单的例子?
查看完整描述

3 回答

?
慕田峪4524236

TA贡献1875条经验 获得超5个赞

除了……之外@Sii的回答,还可以使用setter更新其他值。

function Name(first, last) {
    this.first = first;
    this.last = last;}Name.prototype = {
    get fullName() {
        return this.first + " " + this.last;
    },

    set fullName(name) {
        var names = name.split(" ");
        this.first = names[0];
        this.last = names[1];
    }};

现在,你可以fullName,和firstlast将被更新,反之亦然。


n = new Name('Claude', 'Monet')

n.first # "Claude"

n.last # "Monet"

n.fullName # "Claude Monet"

n.fullName = "Gustav Klimt"

n.first # "Gustav"

n.last # "Klimt"


查看完整回答
反对 回复 2019-07-04
?
斯蒂芬大帝

TA贡献1827条经验 获得超8个赞

例如,您可以使用它们来实现计算的属性。

例如:

function Circle(radius) {
    this.radius = radius;}Object.defineProperty(Circle.prototype, 'circumference', {
    get: function() { return 2*Math.PI*this.radius; }});Object.defineProperty(Circle.prototype, 'area', {
    get: function() { return Math.PI*this.radius*this.radius; }});c = new Circle(10);console.log(c.area); 
    // Should output 314.159console.log(c.circumference); // Should output 62.832

(代码笔)


查看完整回答
反对 回复 2019-07-04
  • 3 回答
  • 0 关注
  • 342 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号