Why are dom events written like this?

  node.js, question

Because I want to judge the compatibility of browser monitoring, so write this below

Element["on "plus type]=handler;

My understanding is that this formula obtains the following sentence pattern


But what I really want is (I think this is right)


Question: Why did he use [] instead of. () to wrap the contents inside? ? Which piece of knowledge is this? ?

JavaScript defines two syntax for attribute access:

Expression.identifier // An expression specifies an object and an identifier specifies the name of the attribute that needs to be accessed
 Expression[expression] // This method is applicable to objects and arrays. The expression in [] specifies the name of the attribute to be accessed or represents the index of the array element to be accessed.

.identifierThe writing of is only applicable to the identifier that the attribute name to be accessed is legal, andYou need to know the name of the attribute you want to access..
When the attribute name is a calculated value instead of a fixed value, square brackets must be used.
(From JavaScript Authoritative Guide Section 4.4-Attribute Access Expression)

Element["on "plus type]=handler;  //type here is a string, so this attribute is formed by concatenation of strings and is calculated. Therefore, access to this attribute can only be written in square brackets.

When the event type (such as click event) is determined, you can register directly as follows:element["onclick"]=handler;(the subject’s code is short of quotation marks) orelement.onclick=handler;