简体   繁体   中英

What does the below snippet mean?

I'm trying to understand the syntax but it all feels new to me. I see an anonymous function in an anonymous function followed by a comma and a class. Please help me understand the syntax..

e => (function(e) {
if ("function" != typeof e.prototype.dispatchEvent) throw new TypeError(`${e} must be an Element type`)
}(e), class extends e {
[i](e, t) {
    n.getService(this).navigateTo(e, {
        replace: t
    })
} [a](e) {
    return n.getService(this).generateUrl(e)
}
})

First of all, this is invalid syntax: NavigationMixin should be followed by an equal sign to be valid.

Secondly, this code references undefined variables a and i .

Let's break it down:

NavigationMixin is a function that takes one argument: e , which should be a class/constructor that is or inherits from Element . The function is an arrow function which uses the arrow expression syntax, meaning there is no block, nor a return statement. The expression that follows => evaluates to the returned value.

The expression consists of the comma operator. The left operand of this operator is:

(function(e) {
  if ("function" != typeof e.prototype.dispatchEvent) throw new TypeError(`${e} must be an Element type`)
}(e)

This is a so-called "immediately invoked function expression" (IIFE). The anonymous function is executed with e as argument, and it clearly serves to perform a validation on e . The function does not return anything, nor would that be useful. It's only purpose is to trigger an error if the validation does not pass.

Then we move to the second operand of the comma operator:

class extends e {
  [i](e, t) {
    n.getService(this).navigateTo(e, {
        replace: t
    })
  } 
  [a](e) {
    return n.getService(this).generateUrl(e)
  }
})

This is a class expression. It defines two members on the prototype. Those members have computed names, which is why they have the [] syntax: The value of i determines the name of the first member and its value is a function:

(e, t) {
  n.getService(this).navigateTo(e, {
      replace: t
  })
}

The second member on the prototype also has a dynamic name, determined by the value of a , and it is also a function.

Finally, the comma operator evaluates the two operands, and ignores the value of the first, and returns the value of the second. So the overall function -- when executed -- returns a class that extends the given class with two methods, whose names are dynamically determined by two variables a and i .

The code does not give a clue about those two variables.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM