Ask a question about javascript this? ?

  node.js, question
var Test={
 // return /android/gi.test(this.UA);

callTest.isAndroideventuateundefinedAt this timethisIt’s not pointing atTestMody

var Test = {}Is a declaration+assignment operation, assignment is to evaluate the expression on the right side of the equal sign first, and then assign the result to the variable on the left side of the equal sign-in other words, it can only be accessed after the assignment is successfulTest.

AndisAndroidIs run when evaluating the expression to the right of the equal sign (IIFE), becauseTestThe assignment has not yet been completed, which IIFE actually accessedthisYeswindow, andwindow.UAIt does not exist, thereforeundefinedNo mistake.

JavaScript is a dynamic language,thisThe direction of is determined by the interpreter when the code is executed. You wrote thisisAndroidIn essence, it is compiled by insidegetterMethod, so do not use IIFE to evaluate automatically at declaration time.

If you don’t want to use itTest.isAndroid()This way to accessthis.UAYou can write JavaScriptget isAndroidMethod, this depends on the ES version you use to determine the specific writing method. You can search JavaScript getter/setter online for further study.

Add a sample. If you have requirements for browser support, make your own conversion or find shim support:

var Test = {
 UA: 'test ua',
 get isAndroid() {
 // 'test ua'