Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

JavaScript getter/setters (S|Get keyword) #49

Open
@jenbutongit

Description

@jenbutongit

👋 hey, this is a great repo/cheatsheet, thanks for this!

A couple points on your get/set examples, in short, they are confusing when compared with each other and conflicts with OO principles.
"Accesses data immediately (i.e. shorthand getter of internal data)."

// GetfunctiongetFruitCount(){returnthis.fruits.length}

this suggests that getFruitCount is part of either a class or object, which has the propertyfruits with type array (or other iterable).

constbowl={fruits:['apple','orange','pear'],getFruitCount(){this.fruits.length},getfruitCount(){this.fruits.length}}

with the example above to get the number of fruits in the bowl, you can do eitherbowl.getFruitCount() orbowl.fruitCount. If you find you are using getFruitCount often in your code, or you are passing it into another function, it can get unreadable/extraneous quite quickly.

thrownewError(`Not enough${bowl.getFruitCount()}`);// vsthrownewError(`Not enough${bowl.fruitCount}`);
// Setletfruits=0functionsetFruits(nextFruits){fruits=nextFruits}setFruits(5)

I think this example should either match your get example, or be completely different so it's not confusing, since get/set on an object is thought of to be a matching pair. Currently, I don't see a "benefit" of using this set function over a simplefruits = randomNumber() orfruits = 5 especially with the current scoping. If you were to match the getter method (get keyword), the example would look like this.

constbowl={fruits:0,getfruitCount(){this.fruits},setfruitCount(val){if(typeofval==='number'){fruits=val}else{thrownewError('You need to provide a number');}}console.log(bowl.fruitCount)// 0;bowl.fruitCount=5;console.log(bowl.fruitCount)// 5;bowl.fruitCount= "invalid";// throws Error

the key words, in js and other languages usually allow for those sorts of protections against setting (and getting a private field without exposing the field's value directly).

To avoid this confusion, I think you should either explain getters/setters vs a function with get/set in the name and provide an example of both, or more simply, use a pure function as an example.

functiongetRandomFruit(){/* returns a fruit */}functionsetTheme(palette){/* changes UI theme to light | dark mode */}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions


      [8]ページ先頭

      ©2009-2025 Movatter.jp