相关疑难解决方法(0)

为什么要使用getter和setter/accessors?

使用getter和setter的优点是什么 - 只能获取和设置 - 而不是简单地使用公共字段来存储这些变量?

如果getter和setter做的不仅仅是简单的get/set,我可以非常快地解决这个问题,但我并不是100%清楚如何:

public String foo;
Run Code Online (Sandbox Code Playgroud)

更糟糕的是:

private String foo;
public void setFoo(String foo) { this.foo = foo; }
public String getFoo() { return foo; }
Run Code Online (Sandbox Code Playgroud)

而前者需要很少的样板代码.

java oop getter setter abstraction

1472
推荐指数
26
解决办法
37万
查看次数

ECMAScript 6课程中的getter和setter是什么?

我对ECMAScript 6类中getter和setter的重点感到困惑.什么目的?以下是我所指的一个例子:

class Employee {

    constructor(name) {
        this._name = name;
    }

    doWork() {
        return `${this._name} is working`;
    }

    get name() {
        return this._name.toUpperCase();
    }

    set name(newName){
        if(newName){ 
            this._name = newName;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

getter setter class ecmascript-6

98
推荐指数
3
解决办法
7万
查看次数

JavaScript中需要`getter`和`setter`吗?

class Employee {

    constructor(name, age) {
        this._name = name;
        this.age = age;
    }

    doWork() {
        return `${this._name} is working`;
    }

    get name() {
        return this._name.toUpperCase();
    }

    set name(newName){
        if(newName){ 
            this._name = newName;
        }
    }
}

let man = new Employee('A', 10);
console.log(man.name, man.age);
man.name = 'B';
man.age = 20;
console.log(man.name, man.age);
Run Code Online (Sandbox Code Playgroud)

这是我的代码.我创建了一个gettersetter_name成员.我没有创建一个gettersetterfor age.

但两者都可以像这样更新这两个字段 man.name = 'B';man.age = 20;

所以,我很困惑,是gettersetter必要在JavaScript?

javascript

13
推荐指数
3
解决办法
5477
查看次数

JavaScript getter 方法的重点是什么?

我试图了解以下优点是什么(如果有的话):

const obj = {
    forename: 'Foo',
    surname: 'Bar',
    get name() {
        //yes I get that I can do other stuff here
        return this.forename+' '+this.surname;
    }
}
alert(obj.name); //Foo Bar
Run Code Online (Sandbox Code Playgroud)

...超过...

const obj = {
    forename: 'Foo',
    surname: 'Bar',
    name() {
        return this.forename+' '+this.surname;
    }
}
alert(obj.name()); //Foo Bar
Run Code Online (Sandbox Code Playgroud)

我已经阅读了 ( 1 ; 2 ; 3 ) 但似乎看不到除了可读性和代码风格之外的任何好处。仅此而已吗?两种方法之间没有隐含的行为变化?

是否只关注 JavaScript 中未来的类属性/方法可见性?这是有道理的 - 私有财产的吸气剂。但是因为那还没有,我看不出上面的意思。

任何人都可以启发我吗?

javascript oop getter-setter ecmascript-5

5
推荐指数
1
解决办法
287
查看次数