Table of Contents
How do getters and setters work?
What’s the problem?
Is seal OK?
The Arrival of Classes
proxy来帮助?
Home Web Front-end JS Tutorial Why is it bad to use getters and setters in JavaScript?

Why is it bad to use getters and setters in JavaScript?

Jul 18, 2017 pm 04:08 PM
getter javascript setter

As you know, getters and setters have become part of JavaScript. They widely support all major browsers, even IE8.

I don't think this idea is generally wrong, but I think it's not very suitable for JavaScript. It may seem that getters and setters simplify code and save time, but they actually introduce hidden errors that are not obvious at first glance.

How do getters and setters work?

First a little summary of what these are:

Sometimes, we want to allow access to a property that returns a dynamically calculated value, or you may want to reflect the state of an internal variable , without using explicit method calls.

To illustrate how they work, let's look at a person object with two properties: firstName and lastName, and a calculated value: fullName.

var obj = {
  firstName: "Maks",
  lastName: "Nemisj"
}
Copy after login

The calculated value fullName will return the concatenation of firstName and lastName.

Object.defineProperty(person, 'fullName', {
  get: function () {
    return this.firstName + ' ' + this.lastName;
  }
});
Copy after login

To get the calculated value of fullName, you don't need the horrible parentheses like person.fullName(), just use simple var fullName = person.fullName.

The same applies to the setter, you can set the value by using the function:

Object.defineProperty(person, 'fullName', {
  set: function (value) {
    var names = value.split(' ');
    this.firstName = names[0];
    this.lastName = names[1];
  }
});
Copy after login

Using is as simple as the getter: person.fullName = ‘Boris Gorbachev’. This will call the function defined above and separate Boris Gorbachev into firstName and lastName.

What’s the problem?

You may be thinking: "Hey, I like the getter and setter methods, they feel more natural, like JSON." You're right, they are, but let's take a step back and look at it. A look at how fullName works before getters and setters.

To get the value we will use something like getFullName(), and to set the value we will use person.setFullName(‘Maks Nemisj’).

What will happen if the function name is misspelled and person.getFullName() is written as person.getFulName()?

JavaScript will give an error:

person.getFulName();
       ^
TypeError: undefined is not a function
Copy after login

This error will be triggered at the appropriate time and in the appropriate place. Accessing an object where the function does not exist will trigger an error - this is good.

Now, let’s see what happens when we use the setter with the wrong name?

person.fulName = 'Boris Gorbachev';
Copy after login

Nothing. Objects are extensible and keys and values ​​can be assigned dynamically, so no errors will be thrown at runtime.

Such behavior means that an error may be displayed somewhere in the user interface, or when some operation is performed on the wrong value, rather than a typographical error.

It's so interesting to track errors that should have occurred in the past but show up in the future code flow.

Is seal OK?

This problem can be partially solved through sealAPI. As long as the object is sealed, it cannot be mutated, which means fulName will try to assign a new key to the person object, and it will fail.

For some reason, when I tested this in Node.js V4.0, it didn't work as I expected. So, I can't guarantee this solution.

What’s even more frustrating is that there is no solution at all for setters. As I mentioned earlier, objects are extensible and failsafe, which means that accessing a non-existent key will not cause any errors.

If this situation only applied to object literals, I wouldn’t bother writing this article, but after ECMAScript 2015 (ES6) and the rise of the ability to define getters and setters with classes, I decided to write Blog about potential pitfalls.

The Arrival of Classes

I know that currently classes are not very popular in some JavaScript communities. People debate whether they are needed in functional/prototype-based languages ​​such as JavaScript. However, the fact is that classes are in the ECMAScript 2015 (ES6) specification and will be there for a while.

To me, classes are a way of specifying a well-defined API between the external world of the class (consumers) and the internal world of the application. This is an abstraction that puts the rules in black and white, and we assume those rules won't change anytime soon.

Improve the person object and make a real class of it. Person defines an interface for getting and setting fullName.

class Person {
  constructor(firstName, lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
  }
  getFullName() {
    return this.firstName + ' ' + this.lastName;
  }
  setFullName(value) {
    var names = value.split(' ');
    this.firstName = names[0];
    this.lastName = names[1];
  }
}
Copy after login

The class defines a strict interface description, but the getter and setter methods make it less strict. We're used to bloated errors when working with object literals and misspellings in keys when working with JSON. I wish at least the classes could be more rigorous and, in that sense, provide better feedback to developers.

Although this situation is no different when defining getters and setters on a class. But it won't stop anyone from spelling it wrong.

class Person {
  constructor(firstName, lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
  }
  get fullName() {
    return this.firstName + ' ' + this.lastName;
  }
  set fullName(value) {
    var names = value.split(' ');
    this.firstName = names[0];
    this.lastName = names[1];
  }
}
Copy after login

Executions with typos will not give any errors:

var person = new Person('Maks', 'Nemisj');
console.log(person.fulName);
Copy after login

The same lax, verbose, and untraceable behavior may lead to errors.

在我发现这一点后,我有一个问题:在使用getter和setter的时候,有没有什么可以做的,以便于使得类更严格?我发现:有是肯定有,但是这值得吗?增加额外层次的复杂性到代码就只是为了使用数量更少的括号?对于API定义,也可以不使用getter和setter,而这样一来就能解决这个问题。除非你是一个铁杆开发人员,并愿意继续进行,不然还有另一种解决方案,如下所述。

proxy来帮助?

除了getter和setter方法,ECMAScript 2015(ES6)还自带proxy对象。proxy可以帮助你确定委托方法,这些委托方法可以在实际访问键执行之前,用来执行各种操作。事实上,它看起来像动态getter / setter方法。

proxy对象可以用来捕捉任何到类的实例的访问,并且如果在类中没有找到预先定义的getter或setter就会抛出错误。

为了做到这一点,必须执行下面两个操作:

  • 创建基于Person原型的getter和setter清单。

  • 创建将测试这些清单的Proxy对象。

让我们来实现它。

首先,为了找出什么样的getter和setter方法可以用在类Person上,可以使用getOwnPropertyNames和getOwnPropertyDescriptor:

var names = Object.getOwnPropertyNames(Person.prototype);
var getters = names.filter((name) => {
  var result =  Object.getOwnPropertyDescriptor(Person.prototype, name);
  return !!result.get;
});
var setters = names.filter((name) => {
  var result =  Object.getOwnPropertyDescriptor(Person.prototype, name);
  return !!result.set;
});
Copy after login

在此之后,创建一个Proxy对象:

var handler = {
  get(target, name) {
    if (getters.indexOf(name) != -1) {
      return target[name];
    }
    throw new Error('Getter "' + name + '" not found in "Person"');
  },
  set(target, name) {
    if (setters.indexOf(name) != -1) {
      return target[name];
    }
    throw new Error('Setter "' + name + '" not found in "Person"');
  }
};
person = new Proxy(person, handler);
Copy after login

现在,只要你尝试访问person.fulName,就会显示Error: Getter “fulName” not found in “Person”的消息。

The above is the detailed content of Why is it bad to use getters and setters in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

How to get HTTP status code in JavaScript the easy way How to get HTTP status code in JavaScript the easy way Jan 05, 2024 pm 01:37 PM

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service

How to use insertBefore in javascript How to use insertBefore in javascript Nov 24, 2023 am 11:56 AM

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

See all articles