使用kotlin2js生成库后,如何从JavaScript访问Kotlin object?
Hey there! I totally get the frustration when the docs are sparse—let's clear up that "lazy object initialization" note and get you accessing those Kotlin objects from JS properly.
What does "lazy object initialization" mean here?
Kotlin's object declarations are singletons, and when compiling to JavaScript, Kotlin preserves their lazy-loaded behavior. That means the singleton instance isn't created automatically when your JS library loads—it only gets initialized the first time you explicitly request it. Unlike regular Kotlin classes (which you instantiate with new in JS, triggering their constructor right away), objects sit dormant until you kick off their initialization.
How to access Kotlin objects in JavaScript
Here are the concrete steps and examples to make this work:
1. Explicitly initialize the object with getInstance()
When kotlin2js compiles a Kotlin object, it generates a getInstance() method that creates (or returns the existing) singleton instance. You need to call this first before accessing any members:
Kotlin code:
object AppConfig { val apiUrl = "https://api.example.com" fun getAuthToken() = "secret-token-123" }
JavaScript code:
// First, initialize the singleton instance const appConfig = AppConfig.getInstance(); // Now you can access its properties and methods console.log(appConfig.apiUrl); // Logs "https://api.example.com" console.log(appConfig.getAuthToken()); // Logs "secret-token-123"
2. Use @JsName to avoid name mangling
Kotlin's compiler might obfuscate function/property names in the compiled JS. To make sure your object and its members have predictable names, add the @JsName annotation in Kotlin:
Kotlin code:
@JsName("AppConfig") object AppConfig { @JsName("apiUrl") val apiUrl = "https://api.example.com" @JsName("getAuthToken") fun getAuthToken() = "secret-token-123" }
This ensures the compiled JS uses the exact names you specify, so you won't run into "undefined" errors from mangled identifiers.
3. Accessing companion objects
If you're dealing with a companion object inside a Kotlin class, the approach is almost identical—you'll access the Companion property and call getInstance() on it:
Kotlin code:
class UserManager { companion object { val maxUsers = 100 fun isUserLimitReached(count: Int) = count >= maxUsers } }
JavaScript code:
const userCompanion = UserManager.Companion.getInstance(); console.log(userCompanion.maxUsers); // Logs 100 console.log(userCompanion.isUserLimitReached(99)); // Logs false
Why regular classes work fine
Regular Kotlin classes compile to JS constructor functions. When you do new MyKotlinClass() in JS, you're immediately triggering the class initialization, which is why you don't run into the same lazy-loading barrier as with objects.
内容的提问来源于stack exchange,提问作者David Vávra

