You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用kotlin2js生成库后,如何从JavaScript访问Kotlin object?

Accessing Kotlin Objects from JavaScript with kotlin2js

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 10:53:53