Get the App
SLTechnology News&Howtos  ›  Development  › 

How to use the JavaScript accessor

Shulou Source: shulou.com Published: 2022-06-01 04:08:38 11月13日 Update

In this article, the editor introduces in detail "how to use the JavaScript accessor". The content is detailed, the steps are clear, and the details are handled properly. I hope this article "how to use the JavaScript accessor" can help you solve your doubts.

JavaScript accessor (Getter and Setter)

Why use Getter and Setter?

It provides a more concise syntax

It allows the syntax of properties and methods to be the same

It ensures better data quality.

It is good for backstage work

JavaScript Getter (get keyword)

This example uses the lang property to get the value of the language property.

Example

/ / create an object:

Var person = {

FirstName: "Bill"

LastName: "Gates"

Language: "en"

Get lang () {

Return this.language

}

}

/ / use getter to display data from objects:

Document.getElementById ("demo"). InnerHTML = person.lang

JavaScript Setter (set keyword)

This example uses the lang property to set the value of the language property.

Example

Var person = {

FirstName: "Bill"

LastName: "Gates"

Language: ""

Set lang (lang) {

This.language = lang

}

}

/ / use setter to set object properties:

Person.lang = "en"

/ / display the data from the object:

Document.getElementById ("demo"). InnerHTML = person.language

JavaScript function or Getter?

What is the difference between the following two examples?

Example 1

Var person = {

FirstName: "Bill"

LastName: "Gates"

FullName: function () {

Return this.firstName + "" + this.lastName

}

}

/ / use methods to display data from objects:

Document.getElementById ("demo"). InnerHTML = person.fullName ()

Example 2

Var person = {

FirstName: "Bill"

LastName: "Gates"

Get fullName () {

Return this.firstName + "" + this.lastName

}

}

/ / use getter to display data from objects:

Document.getElementById ("demo"). InnerHTML = person.fullName

Read here, this article "how to use the JavaScript accessor" article has been introduced, want to grasp the knowledge of this article also need to practice and use to understand, if you want to know more about the article, welcome to follow the industry information channel.

Tags: Object attribute data example article key keyword content instance method grammar proper same concise two usage function background idea new knowledge Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno NVidia Xiaomi Redmi Linux MariaDB