Appearance
注入this用来获取js运行时设置的属性
在类中使用
js
import { QueryEngine } from './index.js'
const qe = new QueryEngine()
qe.refCount = 3
console.log(qe.getRefCount()) // 3
import { QueryEngine } from './index.js'
const qe = new QueryEngine()
qe.refCount = 3
console.log(qe.getRefCount()) // 3
在上面的例子中, QueryEngine 并没有声明和初始化 refCount, 但是js动态设置了,rust要怎么做才能获取到这个属性呢?
rust
#[napi]
use napi::bindgen_prelude::*;
use napi_derive::napi;
pub struct QueryEngine {}
#[napi]
impl QueryEngine {
#[napi(constructor)]
pub fn new() -> Result<Self> {
Ok(Self {})
}
#[napi]
pub fn get_ref_count(&self, this: This) -> Result<Option<i32>> {
this.get::<i32>("refCount")
}
}
#[napi]
use napi::bindgen_prelude::*;
use napi_derive::napi;
pub struct QueryEngine {}
#[napi]
impl QueryEngine {
#[napi(constructor)]
pub fn new() -> Result<Self> {
Ok(Self {})
}
#[napi]
pub fn get_ref_count(&self, this: This) -> Result<Option<i32>> {
this.get::<i32>("refCount")
}
}
在函数中使用
rust
import { Width, plusOne } from './index.js'
const width = new Width(1)
console.log(plusOne(width)) // 2
import { Width, plusOne } from './index.js'
const width = new Width(1)
console.log(plusOne(width)) // 2
在上面的例子中,plusOne可能有自己的this上下文
rust
use napi::bindgen_prelude::*;
use napi_derive::napi;
#[napi(constructor)]
pub struct Width {
pub value: i32,
}
#[napi]
pub fn plus_one(this: This<&Width>) -> i32 {
this.value + 1
}
use napi::bindgen_prelude::*;
use napi_derive::napi;
#[napi(constructor)]
pub struct Width {
pub value: i32,
}
#[napi]
pub fn plus_one(this: This<&Width>) -> i32 {
this.value + 1
}