Summary of calling js methods in Kotlin
This article mainly introduces the relevant information about the detailed explanation of the method instance of calling JavaScript in the Kotlin language. Friends in need can refer to the detailed explanation of the instance of calling the JavaScript method in the Kotlin language.
Kotlin has been designed to easily interoperate with the Java platform. It treats Java classes as Kotlin classes, and Java treats Kotlin classes as Java classes. However, JavaScript is a dynamically typed language, which means it does not check types at compile time. You can freely communicate with JavaScript in Kotlin through dynamic typing, but if you want the full power of the Kotlin type system, you can create Kotlin header files for your JavaScript libraries.
Inline JavaScript
You can embed some JavaScript code into Kotlin code using the js("...") function. For example:
fun jsTypeOf(o: Any): String { return js("typeof o") }
js parameters must be
string
fun jsTypeOf(o: Any): String { return js(getTypeof() + " o") // 此处报错 } fun getTypeof() = "typeof"
external modifier
tells Kotlin that a certain declaration is made in pure JavaScript written, you should mark it with the external modifier. When the compiler sees such a declaration, it assumes that the implementation of the corresponding class, function, or property was provided by the developer, and therefore does not attempt to generate any JavaScript code from the declaration. This means you should omit the body of the external declaration content. For example:
external fun alert(message: Any?): Unit external class Node { val firstChild: Node fun append(child: Node): Node fun removeChild(child: Node): Node // 等等 } external val window: Window
Please note that nested declarations inherit the external modifier, that is, in the Node class, we do not place external before member functions and properties.
Declaring (
) members of a classIn JavaScript, you can define members on the prototype or on the class itself. That is:
function MyClass() { } MyClass.sharedMember = function() { /* 实现 */ }; MyClass.prototype.ownMember = function() { /* 实现 */ };
There is no such syntax in Kotlin. However, in Kotlin we have companion objects. Kotlin treats companion objects of the external class in a special way: instead of expecting an object, it assumes that the members of the companion object are members of the class itself. To describe MyClass from the above example, you could write:
external class MyClass { companion object { fun sharedMember() } fun ownMember() }
Declare optional parameters
An external function can There are optional parameters. How the JavaScript implementation actually calculates the default values of these parameters is unknown to Kotlin, so it is not possible to declare these parameters using the usual syntax in Kotlin. You should use the following syntax:
external fun myFunWithOptionalArgs(x: Int, y: String = definedExternally, z: Long = definedExternally)
This means you can call myFunWithOptionalArgs with one required argument and two optional arguments (their default values are figured out by some JavaScript code ).
Extending JavaScript classes
You can easily extend JavaScript classes because they are Kotlin classes. Just define an external class and extend it with non-external classes. For example:
external open class HTMLElement : Element() { /* 成员 */ } class CustomElement : HTMLElement() { fun foo() { alert("bar") } }
There are some restrictions:
overloaded
, it cannot be derived class override it.Cannot override a function that uses default parameters.
Please note that you cannot extend a non-external class with an external class.
external interface
JavaScript has no concept of interface. When a function expects its arguments to support foo and bar methods, just pass the object that actually has those methods. For statically typed Kotlin, you can express this using interfaces, for example:
external interface HasFooAndBar { fun foo() fun bar() } external fun myFunction(p: HasFooAndBar)
Another use case for external interfaces is to describe settings objects. For example:
external interface JQueryAjaxSettings { var async: Boolean var cache: Boolean var complete: (JQueryXHR, String) -> Unit // 等等 } fun JQueryAjaxSettings(): JQueryAjaxSettings = js("{}") external class JQuery { companion object { fun get(settings: JQueryAjaxSettings): JQueryXHR } } fun sendQuery() { JQuery.get(JQueryAjaxSettings().apply { complete = { (xhr, data) -> window.alert("Request complete") } }) }
External interfaces have some restrictions:
They cannot be used on the right side of an is check. as conversion to an external interface always succeeds (and produces a warning at compile time).
They cannot be passed as reified type parameters. They cannot be used in class literal
expressions
(i.e. I
::class).
The above is the detailed content of Summary of calling js methods in Kotlin. For more information, please follow other related articles on the PHP Chinese website!

Start Spring using IntelliJIDEAUltimate version...

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

Java...

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

How to set the SpringBoot project default run configuration list in Idea using IntelliJ...


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

Atom editor mac version download
The most popular open source editor