一个类
C++ 类会变成 JavaScript 类:new 会运行它的构造函数,它的 public 方法就是 JavaScript 方法。
native.h 在一个和上一课类似的函数下面声明了 Counter。await new Counter(41) 会运行 C++ 构造函数;increment 和 value 是它的 public 方法,而 current 是 private 成员,所以留在 C++ 内部。
对象存在于 C++ 中,JavaScript 持有它的句柄。句柄不再被使用后,垃圾回收器会释放它;对象生命周期介绍了如何更早地释放它。
试一试
再创建一个从 100 开始的计数器,把它递增两次,然后打印两个计数器的值。[■]native.h1#pragma once
#include <string>
// Every public function and class declared here can be called
// from JavaScript.
std::string greet(const std::string &name);
class Counter {
public:
explicit Counter(int start);
int increment();
int value() const;
private:
int current;
};
[■]main.js2import { initNative, Counter } from './native/native.h';
await initNative();
const counter = await new Counter(41);
await counter.increment();
console.log('the counter is at', await counter.value());