侧边栏壁纸
  • 累计撰写 218 篇文章
  • 累计创建 59 个标签
  • 累计收到 5 条评论

NAPI 笔记 07:PropertyDescriptor

barwe
2022-08-30 / 0 评论 / 0 点赞 / 1,173 阅读 / 1,491 字
温馨提示:
本文最后更新于 2023-06-07,若内容或图片失效,请留言反馈。部分素材来自网络,若不小心影响到您的利益,请联系我们删除。

一个Object对象可以调用其DefineProperty()方法或者DefineProperties()方法设置属性。

这两个方法都接受PropertyDescriptor对象数组作为参数。

class PropertyDescriptor

PropertyDescriptor 类有三个重要的静态方法:Accessor(), Function() & Value()

static method Accessor

创建一个与只读属性、或者可读可写属性绑定的 PropertyDescriptor 对象。

该方法可以手动定义属性的 getter & setter 方式。

Value TestGetter(const CallbackInfo& info) {
    return Boolean::New(info.Env(), xxx);
}

void TestSetter(const CallbackInfo& info) {
    xxx = info[0].As<Boolean>();
}

// 一个只读属性
PropertyDescriptor pd1 = PropertyDescriptor::Accessor<TestGetter>("pd1");

// 一个可读可写属性
PropertyDescriptor pd2 = PropertyDescriptor::Accessor<TestGetter, TestSetter>("pd2");

一个正确的 Getters 函数:

using GetterCallback = Value (*)(const CallbackInfo& info);

一个正确的 Setter 函数:

using SetterCallback = void (*)(const CallbackInfo& info);

static method Function

创建一个与函数属性(属性值是一个函数)绑定的 PropertyDescriptor 对象。

需要先定义一个函数:

using AccessorFunction = T (*)(const CallbackInfo& info);
static PropertyDescriptor PropertyDescriptor::Function(Env env, __string__ name, AccessorFunction cb, ...);

example:

Value TestFunction(const CallbackInfo& info) {
    return Boolean::New(info.Env(), true);
}

PropertyDescriptor pd3 = PropertyDescriptor::Function(env, "pd3", TestFunction);

static method Value

创建一个与可读可写属性绑定的 PropertyDescriptor 对象。

PropertyDescriptor pd4 = PropertyDescriptor::Value("pd4", true);

Object::DefineProperties

上面创建的四个 PropertyDescriptor 对象,每个对象包含了属性的名称和属性绑定的内容。

可以将一个 PropertyDescriptor 对象数组绑定到 Object 对象上:

obj.DefineProperties({pd1, pd2, pd3, pd4});

在 JavaScript 中对象将获得 pd1, pd2, pd3, pd4 这四个属性。

0

评论区