在比js.context.X更深的函数上使用数组表示法而不是NSM

时间:2013-06-26 05:20:12

标签: dart dart-js-interop

可以使用Dart中的数组表示法访问js.context之后的所有对象吗?例如,我想转换以下内容以使用数组表示法:

var request = js.context.gapi.client.request(js.map(requestData));

以下数组符号是否有效?

var request = js.context['gapi']['client']['request'](js.map(requestData));

此外,如果尝试访问JavaScript内置方法,是否应该执行以下操作?

js.context['JSON']['stringify'](jsonResp);

2 个答案:

答案 0 :(得分:4)

TL; DR :从r24278开始,对属性使用数组表示法,为方法使用noSuchMethod


使用js.context['gapi']['client']会得到与js.context.gapi.client相同的结果。 Array表示法的主要优点是它避免了noSuchMethod。直到最近,这是解决issue in dart2js where minified does not work with noSuchMethod的唯一方法。这个问题已修复,缩小应该与Dart-JS互操作一起使用。

我前几次做了一点基准测试:

  • 对于属性访问:数组表示法比noSuchMethod快10%左右。 (js.context.xjs.context['x']
  • 对于方法访问:数组表示法比noSuchMethod慢约50%。 (js.context.f()js.context['f']()

最后一个结果由{em> JS 和 Dart 之间js.context['f']()的2次通信解释。一个用于检索函数引用(js.context['f']),另一个用于调用此函数。

最后一个问题,使用noSuchMethod可以增加你的dart2js结果大小(但不是我测试它的地方)。

答案 1 :(得分:1)

这对我有用:

  var hug = new js.Proxy(context['Hug']);

  var hugDatabase = new js.Proxy(context['HugDatabase']);

  hugDatabase['addHug'](hug);

  print(hugDatabase['hugs']['length']);

与此JavaScript交互:

function Hug(strength) {
  this.strength = strength;
}

Hug.prototype.embrace = function(length) {
  return 'Thanks, that was a good hug for ' + length + ' minutes!';
}

Hug.prototype.patBack = function(onDone) {
  onDone('All done.');
}

function HugDatabase() {
  this.hugs = [];
}

HugDatabase.prototype.addHug = function(hug) {
  this.hugs.push(hug);
}

完整示例如下:https://github.com/sethladd/dart-example-js-interop/blob/master/web/dart_js_interop_example.dart