简体   繁体   English

如何通过 JS - Dart 互操作从 JavaScript 访问 `this`?

[英]How do I access `this` from JavaScript via JS - Dart interop?

I need to access a JavaScript object's this from a Dart function.我需要从 Dart 函数访问 JavaScript 对象的this I'm effectively adding a new method to a JavaScript object, via Dart-JS interop.我通过 Dart-JS 互操作有效地向 JavaScript 对象添加了一个新方法。 I need to access properties that are on the JavaScript object from the method defined in Dart.我需要从 Dart 中定义的方法访问 JavaScript 对象上的属性。

The Callback constructor can pass the this from JavaScript. Callback构造函数可以从 JavaScript 传递this According to the API docs for Callback :根据回调API 文档

new Callback.many(Function f, {bool withThis: false})
new Callback.once(Function f, {bool withThis: false})

Here is an example:下面是一个例子:

Dart code:飞镖代码:

import 'dart:html';
import 'package:js/js.dart' as js;

void main() {
  var greeter = js.context['greeter'];
  var msg = greeter['greet']('Bob');
  greeter['doCoolStuff'] = new js.Callback.many(doCoolStuff, withThis: true);
}

doCoolStuff(jsThis) {
  print(jsThis['msg']);
}

Notice the use of withThis: true when creating the Callback.请注意在创建回调时使用withThis: true The this from JavaScript is passed in as the first argument to the callback function. JavaScript 中的this作为回调函数的第一个参数传入。 In this case, I give it a name of jsThis .在这种情况下,我将其命名为jsThis

JavaScript code: JavaScript 代码:

function Greeter() {
  this.msg = 'hello';

  var that = this;
  document.getElementById('clickme').addEventListener('click', function() {
    that.doCoolStuff();
  });
}

Greeter.prototype.greet = function(name) {
  return this.msg + ' ' + name;
}

var greeter = new Greeter();

document.getElementById('clickme').addEventListener('click', function() {
  greeter.doCoolStuff(); // comes from Dart land
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM