我们什么时候需要使用;获得;JavaScript面向对象中的关键字

我们什么时候需要使用;获得;JavaScript面向对象中的关键字,javascript,class,oop,ecmascript-6,get,Javascript,Class,Oop,Ecmascript 6,Get,我正在用JavaScript中的OOP刷新我的记忆,我有点困惑。我只是选择一个项目,并尝试将其转换为OOP。“获取”关键字真的很重要吗?让我们看看下面的代码: class Cipher { constructor (str) { this.str = str; } normalizedPlainText() { return this.str.replace(/\W/g,'').toLowerCase(); } size

我正在用JavaScript中的OOP刷新我的记忆,我有点困惑。我只是选择一个项目,并尝试将其转换为OOP。“获取”关键字真的很重要吗?让我们看看下面的代码:

class Cipher {
    constructor (str) {
        this.str = str;
    }

    normalizedPlainText() {
        return this.str.replace(/\W/g,'').toLowerCase();
    }

    size() {
        return this.normalizedPlainText(this.str).length;
    }

    isValid() {
        if ( this.size(this.str) >= 50 ) return true;
    }

    squareRoot() {
        return parseInt(Math.sqrt(this.size((this.str))));
    }

    nbrRows() {
        return this.squareRoot(this.str);
    }

    get nbrCols() {
        if ( Math.pow(this.squareRoot(this.str), 2) === this.size(this.str)) return this.squareRoot(this.str);
        else return this.squareRoot(this.str) + 1;
    }
}



    const cipher = new Cipher('Your description gives people the information they need to help you answer your question##8.');
    console.log('sqrt '+cipher.squareRoot())
    console.log('Nbr rows ' + cipher.nbrRows()) //good output
    console.log('Nbr cols ' + cipher.nbrCols) // good output too

在设计程序时,我想知道是否可以使用“get”。所以O确实尝试了,正如您在get nbrCols()上看到的那样。如果我将get nbrRows()放入并调用它
cipher.nbrRows()
我会得到一个错误,除非我更改调用它的方式,将其命名为this
cipher.nbrRows
。 所以我的结论是:这取决于你。如果使用“get”,则在不使用()的情况下调用它,或者在不使用()的情况下调用它。
我是错了还是遗漏了什么?

通过使用get语法,您正在向对象添加getter,这些都是在ES5(2009)中引入的

见:

当然,您可以添加一个显式的getProperty函数,而不是使用getter

访问getter时不使用括号

无论你使用哪种技术,都有自己的优势

例如:

让person={
_年龄:42,,
获取年龄(){
log(“getter调用了!”);
把这个还给我;
},
设定年龄(年龄){
log(“setter调用了!”);
这个。_年龄=年龄;
},
getAge(){
把这个还给我;
}
}
console.log(“年龄:”,person.Age);
log(“Age(使用getAge()):”,person.getAge());
//使用setter指定年龄
人.年龄=21岁;
console.log(“年龄(设置后):”,person.Age);

通过使用get语法,您向对象添加了一个getter,这些都是在ES5(2009)中引入的

见:

当然,您可以添加一个显式的getProperty函数,而不是使用getter

访问getter时不使用括号

无论你使用哪种技术,都有自己的优势

例如:

让person={
_年龄:42,,
获取年龄(){
log(“getter调用了!”);
把这个还给我;
},
设定年龄(年龄){
log(“setter调用了!”);
这个。_年龄=年龄;
},
getAge(){
把这个还给我;
}
}
console.log(“年龄:”,person.Age);
log(“Age(使用getAge()):”,person.getAge());
//使用setter指定年龄
人.年龄=21岁;
console.log(“年龄(设置后):”,person.Age);
这取决于你。如果您使用
get
而不使用
()
调用它,或者如果您不使用
get
而使用
()
调用它

是的,没错。如果您希望像访问数据属性一样访问该值,并且仅当计算不改变实例时,才应该使用getter

这取决于你。如果您使用
get
而不使用
()
调用它,或者如果您不使用
get
而使用
()
调用它


是的,没错。如果您希望像访问数据属性一样访问该值,并且只有在计算没有改变您的实例时,才应该使用getter。

如果正确,可以使用
get col()
,然后像调用变量一样调用该函数。您还可以创建一个函数
getCol()
。这样就可以更清楚地看到正在使用函数。这取决于您喜欢什么,但我认为函数更具可读性。您是正确的,您可以使用
get col()
,然后像调用变量一样调用函数。您还可以创建一个函数
getCol()
。这样就可以更清楚地看到正在使用函数。这取决于你喜欢什么,但我认为函数更具可读性。