HarmonyOS 鸿蒙Next javaScriptProxy注册的方法中this异常

HarmonyOS 鸿蒙Next javaScriptProxy注册的方法中this异常

使用web模块,注册函数如下:

.javaScriptProxy({
  object: this,
  name: "MapWebObjectName",
  methodList: ["SetCurrTouchPointCoord"],
  controller: this.webviewController
})

发现,js端调用this的SetCurrTouchPointCoord函数时,函数中的this不起作用,该怎么解,大家有啥方法没?

9 回复

你新建一个class,在struct里new 一个class ,这么使用

class Demo{
 param:string
 
 constructor(value:string){
  this.param=value
  }
}

struct demoStrcuct{

 const demo =new Demo('AAA');
 xxx
 ...
 .javaScriptProxy({
   object: this.demo,
   name: "MapWebObjectName",
   methodList: ["SetCurrTouchPointCoord"],
  controller: this.webviewController
  })
 ...
 xxx
}

更多关于HarmonyOS 鸿蒙Next javaScriptProxy注册的方法中this异常的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


这样子的话,怎么在class Demo的函数里,更新struct demoStrcuct中的变量呢,

struct的变量作用是什么?

如果是作用到class里的话,可以在aboutToAppear()里的话为class赋值。

class只是一个对象函数,真正使用是在struct中初始化赋值的,类似于java里的class定义了对象、属性和方法。具体使用要在struct中,

使用箭头函数后,发现js端传过来的数据无法赋值,如下:

SetCurrTouchPointCoord = (Lon: string, Lat: string): void => {
  try {
    console.log(LOG_TAG, 'MapPage SetCurrTouchPointCoord: ', Lon, Lat);
    this.currTouchPointCoordLon = Lon;
    this.currTouchPointCoordLat = Lat;
  }
  catch (error) {
    console.error(LOG_TAG, 'MapPage SetCurrTouchPointCoord failed with ' + error)
  }
}

这里,更新之后,都变成空了。

JS端调用执行arkts端函数,函数中给@state 变量赋值失败了,我如果不用参数赋值,直接给个常量,则是正确的,奇怪,这种赋值方式和内存有关联吗?

需要把数据发送到struct下,参考下面链接中的 this.customBackFunction = (info: number) => this.customBackFunction

我的这个SetCurrTouchPointCoord函数就在struct下,this也就是这个struct,

图片

在HarmonyOS(鸿蒙)系统中,当使用JavaScriptProxy进行注册并遇到this异常时,通常是因为在JavaScript环境中this的上下文与预期不符。在鸿蒙的JavaScript API中,this的指向问题往往源于事件处理或回调函数中this的上下文被意外改变。

解决这类问题的一种常见方法是使用箭头函数,因为箭头函数不会创建自己的this上下文,它会捕获其所在上下文的this值作为自己的this值。例如,如果你在注册一个事件监听器时遇到了this指向问题,可以尝试将事件处理函数改写为箭头函数:

someObject.on('someEvent', (event) => {
    // 在这里使用 this,它会指向 someObject
    this.handleEvent(event);
});

另外,如果需要在非箭头函数中保持this的正确指向,可以使用.bind(this)方法来显式绑定this,或者在函数外部先保存this的引用,如使用const self = this;,然后在函数内部使用self代替this

如果上述方法仍然无法解决你的问题,可能是由于鸿蒙系统特定的API行为或你的代码中存在其他逻辑错误。此时,建议检查API文档以确保正确使用,并详细审查相关代码逻辑。

如果问题依旧没法解决请联系官网客服,官网地址是 https://www.itying.com/category-93-b0.html

回到顶部