Home > Web Front-end > JS Tutorial > body text

Create chained action classes in JavaScript

PHPz
Release: 2023-09-17 12:13:08
forward
1172 people have browsed it

在 JavaScript 中创建链式操作类

Question

We should create a user-defined data type Streak in JavaScript that can be associated with values and Action Link to any scope 强> or

The value can be one of the following strings -

→ one, two three, four, five, six, seven, eight, nine
Copy after login

The action can be one of the following strings -

→ plus, minus
Copy after login

For example, if we implement the following in the context of a class -

Streak.one.plus.five.minus.three;
Copy after login

then the output should be -

const output = 3;
Copy after login

Output explanation

because the operations that occur are -

1 + 5 - 3 = 3
Copy after login

Example

The following is the code-

Real-time demonstration

const Streak = function() {
   let value = 0;
   const operators = {
      'plus': (a, b) => a + b,
      'minus': (a, b) => a - b
   };
   const numbers = [
      'zero', 'one', 'two', 'three', 'four', 'five',
      'six', 'seven', 'eight', 'nine'
   ];
   Object.keys(operators).forEach((operator) => {
      const operatorFunction = operators[operator];
      const operatorObject = {};
      numbers.forEach((num, index) => {
         Object.defineProperty(operatorObject, num, {
            get: () => value = operatorFunction(value, index)
         });
      });
      Number.prototype[operator] = operatorObject;
   });
   numbers.forEach((num, index) => {
      Object.defineProperty(this, num, {
         get: () => {
            value = index;
            return Number(index);
         }  
      });
   });
};
const streak = new Streak();
console.log(streak.one.plus.five.minus.three);
Copy after login

Output

The following is the console output-

3
Copy after login

The above is the detailed content of Create chained action classes in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!