Javascript getters和setters for dummies? [英] Javascript getters and setters for dummies?

查看:155
本文介绍了Javascript getters和setters for dummies?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在努力让我的头脑不停地吸气而且不会沉没。我读过 JavaScript Getters and Setters 定义Getter和Setter 只是没有得到它。

I've been trying to get my head around getters and setters and its not sinking in. I've read JavaScript Getters and Setters and Defining Getters and Setters and just not getting it.

有人可以明确说明:


  1. getter和setter的目的是什么,

  2. 给出一些非常简单的例子?


推荐答案

除了 @ Sii的答案,setter也可以用来更新其他值。

In addition to @Sii's answer, setters can also be used to update other values.

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 ,以及第一个最后将会更新,反之亦然。

Now, you can set fullName, and first and last will be updated and vice versa.

这篇关于Javascript getters和setters for dummies?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆