【问题标题】:Using array notation instead of NSM on functions deeper then js.context.X在比 js.context.X 更深的函数上使用数组表示法而不是 NSM
【发布时间】:2013-06-26 05:20:11
【问题描述】:

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

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);

【问题讨论】:

    标签: dart dart-js-interop


    【解决方案1】:

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


    使用js.context['gapi']['client'] 得到与js.context.gapi.client 相同的结果。数组表示法的主要优点是它避免了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']()

    最后一个结果可以通过 JSDart 之间的 2 次通信来解释 js.context['f']()。一个用于检索函数引用 (js.context['f']),另一个用于调用此函数。

    最后一个问题,使用noSuchMethod 可以增加您的 dart2js 结果大小(但在我测试过的地方并没有那么多)。

    【讨论】:

      【解决方案2】:

      这对我有用:

        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

      【讨论】:

        猜你喜欢
        • 2010-12-12
        • 1970-01-01
        • 1970-01-01
        • 2017-03-11
        • 2012-12-27
        • 2019-02-14
        • 1970-01-01
        • 2015-08-16
        • 2013-11-26
        相关资源
        最近更新 更多