Update docs

This commit is contained in:
konstin 2018-04-14 17:04:53 +02:00 committed by Alex Crichton
parent e87b32fb22
commit d87e07f45e

View File

@ -536,30 +536,44 @@ available to JS through generated shims. If we take a look at the generated JS
code for this we'll see: code for this we'll see:
```js ```js
import * as wasm from './foo_bg'; import * as wasm from './js_hello_world_bg';
export class Foo {
class ConstructorToken {
constructor(ptr) { constructor(ptr) {
this.ptr = ptr; this.ptr = ptr;
} }
}
export class Foo {
constructor(...args) {
if (args.length === 1 && args[0] instanceof ConstructorToken) {
this.ptr = args[0].ptr;
return;
}
throw new Error('you cannot invoke `new` directly without having a method annotated a constructor');
}
free() { free() {
const ptr = this.ptr; const ptr = this.ptr;
this.ptr = 0; this.ptr = 0;
wasm.__wbindgen_foo_free(ptr); wasm.__wbg_foo_free(ptr);
} }
static new(arg0) { static new(arg0) {
const ret = wasm.foo_new(arg0); const ret = wasm.foo_new(arg0);
return new Foo(ret); return new Foo(new ConstructorToken(ret));
} }
get() { get() {
return wasm.foo_get(this.ptr); const ret = wasm.foo_get(this.ptr);
return ret;
} }
set(arg0) { set(arg0) {
wasm.foo_set(this.ptr, arg0); const ret = wasm.foo_set(this.ptr, arg0);
return ret;
} }
} }
``` ```
@ -573,9 +587,7 @@ to JS:
* Manual memory management is exposed in JS as well. The `free` function is * Manual memory management is exposed in JS as well. The `free` function is
required to be invoked to deallocate resources on the Rust side of things. required to be invoked to deallocate resources on the Rust side of things.
It's intended that `new Foo()` is never used in JS. When `wasm-bindgen` is run To be able to use `new Foo()`, you'd need to annotate `new` as `#[wasm_bindgen(constructor)]`.
with `--debug` it'll actually emit assertions to this effect to ensure that
instances of `Foo` are only constructed with the functions like `Foo.new` in JS.
One important aspect to note here, though, is that once `free` is called the JS One important aspect to note here, though, is that once `free` is called the JS
object is "neutered" in that its internal pointer is nulled out. This means that object is "neutered" in that its internal pointer is nulled out. This means that