JsFunction.apply 不起作用,而 JsObject.callMethod 起作用(飞镖)

JsFunction.apply doesn't work while JsObject.callMethod does work (dart)

我经常遇到这种情况,JsFunction.apply 没有像我预期的那样工作。考虑这个例子:

import "dart:js";
import "dart:html";

void main() {
  var div = querySelector('div');
  var span = new SpanElement()..text = "hello world";
  var js = new JsObject.fromBrowserObject(div);
  js["appendChild"].apply([span]);

  // this one does work:
  // js.callMethod("appendChild", [span]);
}

我希望 js["appendChild"].apply([span]); 的工作方式与 js.callMethod("appendChild", [span]); 完全相同。

另请参阅此演示:https://dartpad.dartlang.org/0f35d76a3c61ba1371f1

适用于 js["appendChild"].apply([span], thisArg: js);

如果您不提供 thisArg,就好像您调用 Function.prototype.apply 时将 null 作为第一个参数。

因此您的 Dart 调用与 js 相同:

var div = document.querySelector('div');
var span = document.createElement("span");
span.innerText = "hello world";
div["appendChild"].apply(null, [span]);

上面js代码的执行导致TypeError: Illegal invocation。要使其工作,您必须使用 div["appendChild"].apply(div, [span]);.

所以这不是 Dart 问题而是 js 问题。