1# 使用JSVM-API接口设置JavaScript对象的属性 2<!--Kit: NDK Development--> 3<!--Subsystem: arkcompiler--> 4<!--Owner: @yuanxiaogou; @string_sz--> 5<!--Designer: @knightaoko--> 6<!--Tester: @test_lzz--> 7<!--Adviser: @fang-jinxu--> 8 9## 简介 10 11使用JSVM-API接口获取和设置JavaScript对象的属性。通过合理使用这些函数,实现更复杂的功能和逻辑。 12 13## 基本概念 14 15在JavaScript对象属性的相关开发中,需要处理JavaScript对象属性,确保正确地访问、设置、删除属性,并了解属性的继承关系和枚举特性。以下是一些关键概念: 16 17- **对象(Object)**:在JavaScript中,对象是一种复合数据类型,它允许存储多个不同类型的值作为一个单独的实体。对象是属性和方法的集合。属性是与对象相关联的值,而方法则是对象可以执行的操作。 18- **属性(Property)**:在JavaScript中,属性是对象特征的键值对。每个属性都有一个名字(也称为键或标识符)和一个值。属性的值可以是任意数据类型,包括基本类型、对象和函数。 19- **可枚举属性(EnumerableProperty)**:在JavaScript中,对象的属性分为可枚举和不可枚举之分,它们是由属性的enumerable值决定的,即内部 “可枚举” 标志设置为true或false。可枚举性决定了属性是否能被 `for...in` 遍历到。 20- **自有属性(OwnProperty)**:自有属性是直接定义在对象上的属性,而不是从原型链继承的。 21 22## 接口说明 23 24| 接口 | 功能说明 | 25|----------------------------|--------------------------------| 26| OH_JSVM_GetPropertyNames | 获取给定对象的所有可枚举属性名称,结果变量将存储一个包含所有可枚举属性名称的JavaScript数组 | 27| OH_JSVM_SetProperty | 为给定对象设置一个属性 | 28| OH_JSVM_GetProperty | 用给定的属性的名称,检索目标对象的属性 | 29| OH_JSVM_HasProperty | 用给定的属性的名称,查询目标对象是否有此属性 | 30| OH_JSVM_DeleteProperty | 用给定的属性的名称,删除目标对象属性 | 31| OH_JSVM_HasOwnProperty | 判断给定Object中是否有名为key的own property。| 32| OH_JSVM_SetNamedProperty | 用给定的属性的名称为目标对象设置属性,此方法等效于调用OH_JSVM_SetProperty, 其中,通过utf8Name传入的字符串用于创建JSVM_Value。| 33| OH_JSVM_GetNamedProperty | 用给定的属性的名称,检索目标对象的属性,此方法等效于调用OH_JSVM_GetProperty, 其中,通过utf8Name传入的字符串用于创建JSVM_Value。| 34| OH_JSVM_HasNamedProperty | 用给定的属性的名称,查询目标对象是否有此属性,此方法等效于使用从作为utf8Name传入的字符串创建的JSVM_Value调用OH_JSVM_HasProperty。| 35| OH_JSVM_DefineProperties | 批量的向给定对象中定义属性 | 36| OH_JSVM_GetAllPropertyNames | 获取给定对象的所有可用属性名称,结果变量将存储一个包含所有可枚举属性名称的JavaScript数组 | 37 38## 使用示例 39 40参考[使用JSVM-API实现JS与C/C++语言交互开发流程](use-jsvm-process.md),本文仅展示接口对应的C++代码。 41 42### OH_JSVM_GetPropertyNames 43 44以字符串数组的形式获取对象的可枚举属性的名称,如果接口调用成功则返回JSVM_OK。 45 46cpp部分代码: 47 48```cpp 49// OH_JSVM_GetPropertyNames的样例方法 50static JSVM_Value GetPropertyNames(JSVM_Env env, JSVM_CallbackInfo info) 51{ 52 // 将obj作为参数传入 53 size_t argc = 1; 54 JSVM_Value args[1] = {nullptr}; 55 OH_JSVM_GetCbInfo(env, info, &argc, args, nullptr, nullptr); 56 // 以字符串数组的形式获取对象的可枚举属性的名称,以result传出 57 JSVM_Value result = nullptr; 58 JSVM_Status status = OH_JSVM_GetPropertyNames(env, args[0], &result); 59 if (status != JSVM_OK) { 60 OH_JSVM_ThrowError(env, nullptr, "Failed to get propertynames"); 61 return nullptr; 62 } else { 63 OH_LOG_INFO(LOG_APP, "JSVM OH_JSVM_GetPropertyNames success"); 64 } 65 return result; 66} 67// GetPropertyNames注册回调 68static JSVM_CallbackStruct param[] = { 69 {.data = nullptr, .callback = GetPropertyNames}, 70}; 71static JSVM_CallbackStruct *method = param; 72// GetPropertyNames方法别名,供JS调用 73static JSVM_PropertyDescriptor descriptor[] = { 74 {"getPropertyNames", nullptr, method++, nullptr, nullptr, nullptr, JSVM_DEFAULT}, 75}; 76 77// 样例测试js 78const char *srcCallNative = R"JS( 79 let obj = '{ data: 0, message: "hello world"}'; 80 let script = getPropertyNames(obj); 81)JS"; 82``` 83<!-- @[oh_jsvm_get_property_names](https://gitcode.com/openharmony/applications_app_samples/blob/master/code/DocsSample/ArkTS/JSVMAPI/JsvmUsageGuide/JsvmAboutProperty/getpropertynames/src/main/cpp/hello.cpp) --> 84 85预期输出结果: 86```ts 87JSVM OH_JSVM_GetPropertyNames success 88``` 89 90### OH_JSVM_SetProperty 91 92将给定的属性与值设置入给定的Object。 93 94cpp部分代码: 95 96```cpp 97// OH_JSVM_SetProperty的样例方法 98static JSVM_Value SetProperty(JSVM_Env env, JSVM_CallbackInfo info) 99{ 100 // 接收js侧传入的三个参数:第一个参数为想要设置的object,第二个参数为属性,第三个参数为属性对应的值 101 size_t argc = 3; 102 JSVM_Value args[3] = {nullptr}; 103 JSVM_Status status = OH_JSVM_GetCbInfo(env, info, &argc, args, nullptr, nullptr); 104 if (status != JSVM_OK) { 105 OH_JSVM_ThrowError(env, nullptr, "JSVM OH_JSVM_GetCbInfo fail"); 106 return nullptr; 107 } 108 // 通过调用OH_JSVM_SetProperty接口将属性与值设置入object如果失败,直接抛出错误 109 status = OH_JSVM_SetProperty(env, args[0], args[1], args[2]); 110 if (status != JSVM_OK) { 111 OH_JSVM_ThrowError(env, nullptr, "JSVM OH_JSVM_SetProperty fail"); 112 return nullptr; 113 } else { 114 OH_LOG_INFO(LOG_APP, "JSVM OH_JSVM_SetProperty success"); 115 } 116 // 将设置成功后的object返回出去 117 return args[0]; 118} 119// SetProperty注册回调 120static JSVM_CallbackStruct param[] = { 121 {.data = nullptr, .callback = SetProperty}, 122}; 123static JSVM_CallbackStruct *method = param; 124// SetProperty方法别名,供JS调用 125static JSVM_PropertyDescriptor descriptor[] = { 126 {"setProperty", nullptr, method++, nullptr, nullptr, nullptr, JSVM_DEFAULT}, 127}; 128 129// 样例测试js 130const char *srcCallNative = R"JS( 131 let obj = { data: 0, message: "hello world", 50: 1}; 132 setProperty(obj, "code", "hi") 133)JS"; 134``` 135<!-- @[oh_jsvm_set_property](https://gitcode.com/openharmony/applications_app_samples/blob/master/code/DocsSample/ArkTS/JSVMAPI/JsvmUsageGuide/JsvmAboutProperty/setproperty/src/main/cpp/hello.cpp) --> 136 137预期输出结果: 138```ts 139JSVM OH_JSVM_SetProperty success 140``` 141 142### OH_JSVM_GetProperty 143 144获取给定Object的给定属性对应的值。 145 146cpp部分代码: 147 148```cpp 149// OH_JSVM_GetProperty的样例方法 150static JSVM_Value GetProperty(JSVM_Env env, JSVM_CallbackInfo info) 151{ 152 // 接收两个js传来的参数 153 size_t argc = 2; 154 JSVM_Value args[2] = {nullptr}; 155 OH_JSVM_GetCbInfo(env, info, &argc, args, nullptr, nullptr); 156 // 传入的第一个参数为要检测的object,第二个对象为要检测的属性,通过调用OH_JSVM_GetProperty接口获取对应的值 157 JSVM_Value result = nullptr; 158 JSVM_Status status = OH_JSVM_GetProperty(env, args[0], args[1], &result); 159 if (status != JSVM_OK) { 160 OH_JSVM_ThrowError(env, nullptr, "JSVM OH_JSVM_GetProperty fail"); 161 return nullptr; 162 } else { 163 OH_LOG_INFO(LOG_APP, "JSVM OH_JSVM_GetProperty success"); 164 } 165 return result; 166} 167// GetProperty注册回调 168static JSVM_CallbackStruct param[] = { 169 {.data = nullptr, .callback = GetProperty}, 170}; 171static JSVM_CallbackStruct *method = param; 172// GetProperty方法别名,供JS调用 173static JSVM_PropertyDescriptor descriptor[] = { 174 {"getProperty", nullptr, method++, nullptr, nullptr, nullptr, JSVM_DEFAULT}, 175}; 176 177// 样例测试js 178const char *srcCallNative = R"JS( 179 let obj = { data: 0, message: "hello world", 50: 1}; 180 getProperty(obj, "message") 181)JS"; 182``` 183<!-- @[oh_jsvm_get_property](https://gitcode.com/openharmony/applications_app_samples/blob/master/code/DocsSample/ArkTS/JSVMAPI/JsvmUsageGuide/JsvmAboutProperty/getproperty/src/main/cpp/hello.cpp) --> 184 185预期输出结果: 186```ts 187JSVM OH_JSVM_GetProperty success 188``` 189 190### OH_JSVM_HasProperty 191 192检查对象中是否存在指定的属性,可以避免访问不存在属性导致的异常或错误。 193 194cpp部分代码: 195 196```cpp 197// OH_JSVM_HasProperty的样例方法 198static JSVM_Value HasProperty(JSVM_Env env, JSVM_CallbackInfo info) 199{ 200 // 从js侧传入两个参数:第一个参数为要检验的对象,第二个参数为要检测是否存在对象的属性 201 size_t argc = 2; 202 JSVM_Value args[2] = {nullptr}; 203 OH_JSVM_GetCbInfo(env, info, &argc, args, nullptr, nullptr); 204 // 将参数传入OH_JSVM_HasProperty方法中,若接口调用成功则将结果转化为JSVM_Value类型抛出,否则抛出错误 205 bool result = false; 206 JSVM_Status status = OH_JSVM_HasProperty(env, args[0], args[1], &result); 207 if (status != JSVM_OK) { 208 OH_JSVM_ThrowError(env, nullptr, "JSVM OH_JSVM_HasProperty fail"); 209 return nullptr; 210 } else { 211 OH_LOG_INFO(LOG_APP, "JSVM OH_JSVM_HasProperty success:%{public}d", result); 212 } 213 // 若传入属性存在传入对象中,则输出true将结果转化为JSVM_Value类型抛出 214 JSVM_Value returnResult = nullptr; 215 OH_JSVM_GetBoolean(env, result, &returnResult); 216 return returnResult; 217} 218// HasProperty注册回调 219static JSVM_CallbackStruct param[] = { 220 {.data = nullptr, .callback = HasProperty}, 221}; 222static JSVM_CallbackStruct *method = param; 223// HasProperty方法别名,供JS调用 224static JSVM_PropertyDescriptor descriptor[] = { 225 {"hasProperty", nullptr, method++, nullptr, nullptr, nullptr, JSVM_DEFAULT}, 226}; 227 228// 样例测试js 229const char *srcCallNative = R"JS( 230 let obj = { data: 0, message: "hello world", 50: 1}; 231 hasProperty(obj, "data") 232 hasProperty(obj, 0) 233)JS"; 234``` 235<!-- @[oh_jsvm_has_property](https://gitcode.com/openharmony/applications_app_samples/blob/master/code/DocsSample/ArkTS/JSVMAPI/JsvmUsageGuide/JsvmAboutProperty/hasproperty/src/main/cpp/hello.cpp) --> 236 237预期输出结果: 238```ts 239// hasProperty(obj, "data")输出 240JSVM OH_JSVM_HasProperty success:1 241// hasProperty(obj, 0)输出 242JSVM OH_JSVM_HasProperty success:0 243``` 244 245### OH_JSVM_DeleteProperty 246 247尝试从给定的Object中删除由key指定的属性,并返回操作的结果。 248如果对象是一个不可扩展的对象,或者属性是不可配置的,则可能无法删除该属性。 249 250cpp部分代码: 251 252```cpp 253// OH_JSVM_DeleteProperty的样例方法 254static JSVM_Value DeleteProperty(JSVM_Env env, JSVM_CallbackInfo info) 255{ 256 // 获取js侧传入的两个参数 257 size_t argc = 2; 258 JSVM_Value args[2] = {nullptr}; 259 OH_JSVM_GetCbInfo(env, info, &argc, args, nullptr, nullptr); 260 JSVM_ValueType valueType; 261 OH_JSVM_Typeof(env, args[0], &valueType); 262 if (valueType != JSVM_OBJECT) { 263 OH_JSVM_ThrowError(env, nullptr, "Expects an object as argument."); 264 return nullptr; 265 } 266 // 从传入的Object对象中删除指定属性,返回是否删除成功的bool结果值 267 bool result = false; 268 JSVM_Status status = OH_JSVM_DeleteProperty(env, args[0], args[1], &result); 269 if (status != JSVM_OK) { 270 OH_JSVM_ThrowError(env, nullptr, "JSVM OH_JSVM_DeleteProperty failed"); 271 return nullptr; 272 } else { 273 OH_LOG_INFO(LOG_APP, "JSVM OH_JSVM_DeleteProperty success:%{public}d", result); 274 } 275 // 将bool结果转换为JSVM_value并返回 276 JSVM_Value ret; 277 OH_JSVM_GetBoolean(env, result, &ret); 278 return ret; 279} 280// DeleteProperty注册回调 281static JSVM_CallbackStruct param[] = { 282 {.data = nullptr, .callback = DeleteProperty}, 283}; 284static JSVM_CallbackStruct *method = param; 285// DeleteProperty方法别名,供JS调用 286static JSVM_PropertyDescriptor descriptor[] = { 287 {"deleteProperty", nullptr, method++, nullptr, nullptr, nullptr, JSVM_DEFAULT}, 288}; 289 290// 样例测试js 291const char *srcCallNative = R"JS( 292 let obj = { data: 0, message: "hello world", 50: 1}; 293 deleteProperty(obj, "message") 294)JS"; 295``` 296<!-- @[oh_jsvm_delete_property](https://gitcode.com/openharmony/applications_app_samples/blob/master/code/DocsSample/ArkTS/JSVMAPI/JsvmUsageGuide/JsvmAboutProperty/deleteproperty/src/main/cpp/hello.cpp) --> 297 298预期输出结果: 299```ts 300JSVM OH_JSVM_DeleteProperty success:1 301``` 302 303### OH_JSVM_HasOwnProperty 304 305用于检查传入的Object是否具有自己的命名属性,不包括从原型链上继承的属性。 306 307cpp部分代码: 308 309```cpp 310// OH_JSVM_HasOwnProperty的样例方法 311static JSVM_Value HasOwnProperty(JSVM_Env env, JSVM_CallbackInfo info) 312{ 313 // 获取js侧传入的两个参数 314 size_t argc = 2; 315 JSVM_Value args[2] = {nullptr}; 316 OH_JSVM_GetCbInfo(env, info, &argc, args, nullptr, nullptr); 317 // 检查第一个参数是否为对象 318 JSVM_ValueType valueType1; 319 OH_JSVM_Typeof(env, args[0], &valueType1); 320 if (valueType1 != JSVM_OBJECT) { 321 OH_JSVM_ThrowError(env, nullptr, "First argument must be an object."); 322 return nullptr; 323 } 324 // 检查第二个参数是否为string 325 JSVM_ValueType valuetype2; 326 OH_JSVM_Typeof(env, args[1], &valuetype2); 327 if (valuetype2 != JSVM_STRING ) { 328 OH_JSVM_ThrowError(env, nullptr, "Second argument must be a string."); 329 return nullptr; 330 } 331 // 检查对象是否具有指定属性,结果存储在hasProperty中 332 bool hasProperty = false; 333 JSVM_Status status = OH_JSVM_HasOwnProperty(env, args[0], args[1], &hasProperty); 334 if (status != JSVM_OK) { 335 OH_JSVM_ThrowError(env, nullptr, "JSVM OH_JSVM_HasOwnProperty failed"); 336 return nullptr; 337 } else { 338 OH_LOG_INFO(LOG_APP, "JSVM OH_JSVM_HasOwnProperty success:%{public}d", hasProperty); 339 } 340 // 将bool结果转换为JSVM_Value并返回 341 JSVM_Value result; 342 OH_JSVM_GetBoolean(env, hasProperty, &result); 343 return result; 344} 345// HasOwnProperty注册回调 346static JSVM_CallbackStruct param[] = { 347 {.data = nullptr, .callback = HasOwnProperty}, 348}; 349static JSVM_CallbackStruct *method = param; 350// HasOwnProperty方法别名,供JS调用 351static JSVM_PropertyDescriptor descriptor[] = { 352 {"hasOwnProperty", nullptr, method++, nullptr, nullptr, nullptr, JSVM_DEFAULT}, 353}; 354 355// 样例测试js 356const char *srcCallNative = R"JS( 357 let obj = { data: 0, message: "hello world", 50: 1}; 358 hasOwnProperty(obj, "message") 359 hasOwnProperty(obj, "__defineGetter__") 360)JS"; 361``` 362<!-- @[oh_jsvm_has_own_property](https://gitcode.com/openharmony/applications_app_samples/blob/master/code/DocsSample/ArkTS/JSVMAPI/JsvmUsageGuide/JsvmAboutProperty/hasownproperty/src/main/cpp/hello.cpp) --> 363 364预期输出结果: 365```ts 366// hasOwnProperty(obj, "message")输出 367JSVM OH_JSVM_HasOwnProperty success:1 368// hasOwnProperty(obj, "__defineGetter__")输出 369// `__defineGetter__`为Object原型方法,非OwnProperty,预期返回0 370JSVM OH_JSVM_HasOwnProperty success:0 371``` 372 373### OH_JSVM_SetNamedProperty 374 375用于在传入的Javascript对象上设置一个命名属性。 376 377cpp部分代码: 378 379```cpp 380// OH_JSVM_SetNamedProperty的样例方法 381static JSVM_Value SetNamedProperty(JSVM_Env env, JSVM_CallbackInfo info) 382{ 383 // 获取js侧传入的一个参数 384 size_t argc = 1; 385 JSVM_Value str; 386 char strKey[32] = ""; 387 OH_JSVM_GetCbInfo(env, info, &argc, &str, nullptr, nullptr); 388 // 获取传入参数字符串并存储在strKey中 389 size_t keyLength = 0; 390 OH_JSVM_GetValueStringUtf8(env, str, strKey, 32, &keyLength); 391 // 创建一个新对象 392 JSVM_Value newObj; 393 OH_JSVM_CreateObject(env, &newObj); 394 // 设置整数值1234为属性值 395 int32_t value = 1234; 396 JSVM_Value numValue; 397 OH_JSVM_CreateInt32(env, value, &numValue); 398 // 将整数值与指定属性名关联 399 JSVM_Status status = OH_JSVM_SetNamedProperty(env, newObj, strKey, numValue); 400 if (status != JSVM_OK) { 401 OH_JSVM_ThrowError(env, nullptr, "JSVM OH_JSVM_SetNamedProperty failed"); 402 return nullptr; 403 } else { 404 OH_LOG_INFO(LOG_APP, "JSVM OH_JSVM_SetNamedProperty success"); 405 } 406 // 返回新创建并设置命名属性的对象 407 return newObj; 408} 409// SetNamedProperty注册回调 410static JSVM_CallbackStruct param[] = { 411 {.data = nullptr, .callback = SetNamedProperty}, 412}; 413static JSVM_CallbackStruct *method = param; 414// SetNamedProperty方法别名,供JS调用 415static JSVM_PropertyDescriptor descriptor[] = { 416 {"setNamedProperty", nullptr, method++, nullptr, nullptr, nullptr, JSVM_DEFAULT}, 417}; 418 419// 样例测试js 420const char *srcCallNative = R"JS( 421 setNamedProperty("message") 422)JS"; 423``` 424<!-- @[oh_jsvm_set_named_property](https://gitcode.com/openharmony/applications_app_samples/blob/master/code/DocsSample/ArkTS/JSVMAPI/JsvmUsageGuide/JsvmAboutProperty/setnamedproperty/src/main/cpp/hello.cpp) --> 425 426预期输出结果: 427```ts 428JSVM OH_JSVM_SetNamedProperty success 429``` 430 431### OH_JSVM_GetNamedProperty 432 433用于从Javascript对象中获取命名属性的值。 434 435cpp部分代码: 436 437```cpp 438// OH_JSVM_GetNamedProperty的样例方法 439static JSVM_Value GetNamedProperty(JSVM_Env env, JSVM_CallbackInfo info) 440{ 441 // 获取js侧传入的两个参数 442 size_t argc = 2; 443 JSVM_Value args[2] = {nullptr}; 444 char strKey[32] = ""; 445 OH_JSVM_GetCbInfo(env, info, &argc, args, nullptr, nullptr); 446 // 获取要获取的属性名 447 size_t keyLength = 0; 448 OH_JSVM_GetValueStringUtf8(env, args[1], strKey, 32, &keyLength); 449 // 获取指定属性的值并存储在result中 450 JSVM_Value result; 451 JSVM_Status status = OH_JSVM_GetNamedProperty(env, args[0], strKey, &result); 452 if (status != JSVM_OK) { 453 OH_JSVM_ThrowError(env, nullptr, "JSVM OH_JSVM_GetNamedProperty failed"); 454 return nullptr; 455 } else { 456 OH_LOG_INFO(LOG_APP, "JSVM OH_JSVM_GetNamedProperty success"); 457 } 458 return result; 459} 460// GetNamedProperty注册回调 461static JSVM_CallbackStruct param[] = { 462 {.data = nullptr, .callback = GetNamedProperty}, 463}; 464static JSVM_CallbackStruct *method = param; 465// GetNamedProperty方法别名,供JS调用 466static JSVM_PropertyDescriptor descriptor[] = { 467 {"getNamedProperty", nullptr, method++, nullptr, nullptr, nullptr, JSVM_DEFAULT}, 468}; 469 470// 样例测试js 471const char *srcCallNative = R"JS( 472 let obj = { data: 0, message: "hello world", 50: 1}; 473 getNamedProperty(obj, "message") 474)JS"; 475``` 476<!-- @[oh_jsvm_get_named_property](https://gitcode.com/openharmony/applications_app_samples/blob/master/code/DocsSample/ArkTS/JSVMAPI/JsvmUsageGuide/JsvmAboutProperty/getnamedproperty/src/main/cpp/hello.cpp) --> 477 478预期输出结果: 479```ts 480JSVM OH_JSVM_GetNamedProperty success 481``` 482 483### OH_JSVM_HasNamedProperty 484 485用于检查Javascript对象中是否包含指定的命名属性。 486 487cpp部分代码: 488 489```cpp 490// OH_JSVM_HasNamedProperty的样例方法 491static JSVM_Value HasNamedProperty(JSVM_Env env, JSVM_CallbackInfo info) 492{ 493 // 获取js侧传入的两个参数 494 size_t argc = 2; 495 JSVM_Value args[2] = {nullptr}; 496 char strKey[32] = ""; 497 OH_JSVM_GetCbInfo(env, info, &argc, args, nullptr, nullptr); 498 // 获取要检查的属性名 499 size_t keyLength = 0; 500 OH_JSVM_GetValueStringUtf8(env, args[1], strKey, 32, &keyLength); 501 // 检查对象是否具有指定命名的属性,并将结果存储在hasProperty中 502 bool hasProperty = false; 503 JSVM_Status status = OH_JSVM_HasNamedProperty(env, args[0], strKey, &hasProperty); 504 if (status != JSVM_OK) { 505 OH_JSVM_ThrowError(env, nullptr, "JSVM OH_JSVM_HasNamedProperty failed"); 506 return nullptr; 507 } else { 508 OH_LOG_INFO(LOG_APP, "JSVM OH_JSVM_HasNamedProperty success:%{public}d", hasProperty); 509 } 510 // 将bool结果转换为JSVM_Value并返回 511 JSVM_Value result; 512 OH_JSVM_GetBoolean(env, hasProperty, &result); 513 return result; 514} 515// HasNamedProperty注册回调 516static JSVM_CallbackStruct param[] = { 517 {.data = nullptr, .callback = HasNamedProperty}, 518}; 519static JSVM_CallbackStruct *method = param; 520// HasNamedProperty方法别名,供JS调用 521static JSVM_PropertyDescriptor descriptor[] = { 522 {"hasNamedProperty", nullptr, method++, nullptr, nullptr, nullptr, JSVM_DEFAULT}, 523}; 524 525// 样例测试js 526const char *srcCallNative = R"JS( 527 let obj = { data: 0, message: "hello world", 50: 1}; 528 hasNamedProperty(obj, "message") 529)JS"; 530``` 531<!-- @[oh_jsvm_has_named_property](https://gitcode.com/openharmony/applications_app_samples/blob/master/code/DocsSample/ArkTS/JSVMAPI/JsvmUsageGuide/JsvmAboutProperty/hasnamedproperty/src/main/cpp/hello.cpp) --> 532 533预期输出结果: 534```ts 535JSVM OH_JSVM_HasNamedProperty success:1 536``` 537 538### OH_JSVM_DefineProperties 539 540用于定义对象的自定义属性,可一次性为对象设置若干个属性。 541 542cpp部分代码: 543 544```cpp 545#include <fstream> 546#include <string> 547// 属性描述符列表中defineMethodPropertiesExample属性的回调函数 548static JSVM_Value DefineMethodPropertiesExample(JSVM_Env env, JSVM_CallbackInfo info) 549{ 550 int32_t propValue = 26; 551 JSVM_Value returnValue; 552 OH_JSVM_CreateInt32(env, propValue, &returnValue); 553 return returnValue; 554} 555// 属性描述符列表中getterCallback属性的回调函数 556static JSVM_Value GetterCallback(JSVM_Env env, JSVM_CallbackInfo info) 557{ 558 JSVM_Value result; 559 const char *str = "Hello world!"; 560 size_t length = strlen(str); 561 // 创建属性的值 562 OH_JSVM_CreateStringUtf8(env, str, length, &result); 563 return result; 564} 565 566// 执行JavaScript字符串的函数 567static JSVM_Value RunScriptAndLogResult(JSVM_Env env, const std::string &srcCode) { 568 JSVM_Value sourceCodeValue; 569 OH_JSVM_CreateStringUtf8(env, srcCode.c_str(), srcCode.size(), &sourceCodeValue); 570 JSVM_Script script; 571 // 编译JavaScript代码字符串并返回编译后的脚本 572 OH_JSVM_CompileScript(env, sourceCodeValue, nullptr, 0, true, nullptr, &script); 573 JSVM_Value jsVmResult; 574 // 执行JavaScript代码字符串 575 OH_JSVM_RunScript(env, script, &jsVmResult); 576 return jsVmResult; 577} 578 579// OH_JSVM_DefineProperties的样例方法 580static JSVM_Value DefineProperties(JSVM_Env env, JSVM_CallbackInfo info) { 581 // 接受一个JavaScript侧传入的空object 582 size_t argc = 1; 583 JSVM_Value argv[1] = {nullptr}; 584 OH_JSVM_GetCbInfo(env, info, &argc, argv, nullptr, nullptr); 585 // 创建一个string类型的属性值 586 JSVM_Value stringValue; 587 OH_JSVM_CreateStringUtf8(env, "Hello!", JSVM_AUTO_LENGTH, &stringValue); 588 // 创建属性描述符对应的回调函数列表 589 JSVM_CallbackStruct param[] = { 590 {.data = nullptr, .callback = DefineMethodPropertiesExample}, 591 {.data = nullptr, .callback = GetterCallback}, 592 593 }; 594 // 创建属性描述符列表,不同类型属性值添加位置参考JSVM_PropertyDescriptor定义 595 JSVM_PropertyDescriptor descriptor[] = { 596 // 定义method类型的属性值 597 {"defineMethodPropertiesExample", nullptr, ¶m[0], nullptr, nullptr, nullptr, JSVM_DEFAULT}, 598 // 定义string类型的属性值 599 {"defineStringPropertiesExample", nullptr, nullptr, nullptr, nullptr, stringValue, JSVM_DEFAULT}, 600 // 定义getter类型的属性值 601 {"getterCallback", nullptr, nullptr, ¶m[1], nullptr, nullptr,JSVM_DEFAULT}}; 602 // 根据属性描述符列表为obj对象创建属性 603 JSVM_Status statusProperty; 604 statusProperty = OH_JSVM_DefineProperties(env, *argv, sizeof(descriptor) / sizeof(descriptor[0]), descriptor); 605 if (statusProperty != JSVM_OK) { 606 OH_JSVM_ThrowError(env, nullptr, "JSVM DefineProperties fail"); 607 return nullptr; 608 } 609 // 调用obj对象中添加的属性 610 // 运行obj.defineMethodPropertiesExample()并将结果返回给JavaScript 611 static std::string srcMethod; 612 srcMethod = R"JS(obj.defineMethodPropertiesExample();)JS"; 613 JSVM_Value jsVmResult = RunScriptAndLogResult(env, srcMethod); 614 if (jsVmResult != nullptr) { 615 int32_t number; 616 OH_JSVM_GetValueInt32(env, jsVmResult, &number); 617 OH_LOG_INFO(LOG_APP, "JSVM DefineMethodPropertiesExample success:%{public}d", number); 618 } 619 // 运行obj.defineStringPropertiesExample()并将结果返回给JavaScript 620 static std::string srcString; 621 srcString = R"JS(obj.defineStringPropertiesExample;)JS"; 622 JSVM_Value jsVmResult1 = RunScriptAndLogResult(env, srcString); 623 if (jsVmResult1 != nullptr) { 624 size_t length = 0; 625 OH_JSVM_GetValueStringUtf8(env, jsVmResult1, nullptr, 0, &length); 626 char *buf = (char *)malloc(length + 1); 627 if (buf == nullptr) { 628 OH_LOG_ERROR(LOG_APP, "malloc failed"); 629 return nullptr; 630 } 631 memset(buf, 0, length + 1); 632 OH_JSVM_GetValueStringUtf8(env, jsVmResult1, buf, length + 1, &length); 633 OH_LOG_INFO(LOG_APP, "JSVM defineStringPropertiesExample success:%{public}s", buf); 634 free(buf); 635 } 636 // 调用obj的getterCallback()并将结果字符串返回给JavaScript 637 static std::string srcGetter; 638 srcGetter = R"JS(obj.getterCallback;)JS"; 639 JSVM_Value jsVmResult2 = RunScriptAndLogResult(env, srcGetter); 640 if (jsVmResult2 != nullptr) { 641 size_t length = 0; 642 OH_JSVM_GetValueStringUtf8(env, jsVmResult2, nullptr, 0, &length); 643 char *buf = (char *)malloc(length + 1); 644 if (buf == nullptr) { 645 OH_LOG_ERROR(LOG_APP, "malloc failed"); 646 return nullptr; 647 } 648 memset(buf, 0, length + 1); 649 OH_JSVM_GetValueStringUtf8(env, jsVmResult2, buf, length + 1, &length); 650 OH_LOG_INFO(LOG_APP, "JSVM getterCallback success:%{public}s", buf); 651 free(buf); 652 } 653 return jsVmResult; 654} 655 656// DefineProperties注册回调 657static JSVM_CallbackStruct param[] = { 658 {.data = nullptr, .callback = DefineProperties}, 659}; 660static JSVM_CallbackStruct *method = param; 661// DefineProperties方法别名,供JS调用 662static JSVM_PropertyDescriptor descriptor[] = { 663 {"defineProperties", nullptr, method++, nullptr, nullptr, nullptr, JSVM_DEFAULT}, 664}; 665 666// 样例测试js 667const char *srcCallNative = R"JS( 668 let obj = {}; 669 defineProperties(obj) 670)JS"; 671``` 672<!-- @[oh_jsvm_define_properties](https://gitcode.com/openharmony/applications_app_samples/blob/master/code/DocsSample/ArkTS/JSVMAPI/JsvmUsageGuide/JsvmAboutProperty/defineproperties/src/main/cpp/hello.cpp) --> 673 674预期输出结果: 675```ts 676JSVM DefineMethodPropertiesExample success:26 677JSVM defineStringPropertiesExample success:Hello! 678JSVM getterCallback success:Hello world! 679``` 680 681### OH_JSVM_GetAllPropertyNames 682 683获取给定对象的所有可枚举属性名称,结果变量将存储一个包含这些属性名称的JavaScript数组。 684 685cpp部分代码: 686 687```cpp 688// OH_JSVM_GetAllPropertyNames的样例方法 689static JSVM_Value GetAllPropertyNames(JSVM_Env env, JSVM_CallbackInfo info) 690{ 691 // 获取js侧传入的一个参数 692 size_t argc = 1; 693 JSVM_Value args[1]; 694 OH_JSVM_GetCbInfo(env, info, &argc, args, nullptr, nullptr); 695 // 获取给定对象的所有属性名称(自有属性) 696 JSVM_Value result; 697 JSVM_Status status = OH_JSVM_GetAllPropertyNames(env, args[0], 698 JSVM_KeyCollectionMode::JSVM_KEY_OWN_ONLY, 699 JSVM_KeyFilter::JSVM_KEY_WRITABLE, 700 JSVM_KeyConversion::JSVM_KEY_NUMBERS_TO_STRINGS, &result); 701 if (status != JSVM_OK) { 702 OH_JSVM_ThrowError(env, nullptr, "Failed to get allpropertynames"); 703 return nullptr; 704 } else { 705 OH_LOG_INFO(LOG_APP, "JSVM OH_JSVM_GetAllPropertyNames success"); 706 } 707 return result; 708} 709// GetAllPropertyNames注册回调 710static JSVM_CallbackStruct param[] = { 711 {.data = nullptr, .callback = GetAllPropertyNames}, 712}; 713static JSVM_CallbackStruct *method = param; 714// GetAllPropertyNames方法别名,供JS调用 715static JSVM_PropertyDescriptor descriptor[] = { 716 {"getAllPropertyNames", nullptr, method++, nullptr, nullptr, nullptr, JSVM_DEFAULT}, 717}; 718 719// 样例测试js 720const char *srcCallNative = R"JS( 721 let obj = '{ data: 0, message: "hello world", 50: 1}'; 722 let script = getAllPropertyNames(obj); 723)JS"; 724``` 725<!-- @[oh_jsvm_get_all_property_names](https://gitcode.com/openharmony/applications_app_samples/blob/master/code/DocsSample/ArkTS/JSVMAPI/JsvmUsageGuide/JsvmAboutProperty/getallpropertynames/src/main/cpp/hello.cpp) --> 726 727预期输出结果: 728```ts 729JSVM OH_JSVM_GetAllPropertyNames success 730``` 731