如何从 Dart 检查 JavaScript 函数是否存在

How to check for a JavaScript function's existence from Dart

在通过 JS 互操作调用它之前,我想检查 Dart 中是否存在顶级 JavaScript 函数。我认为以某种方式公开 typeof JS 运算符会有所帮助,但无法使其正常工作。

我尝试过的东西。

使用package:js:

@JS()
library existence_check;

import 'package:js/js.dart';

@JS()
external void someJsFunction(String input);

@JS()
external String typeof(object);

String check() => typeof(someJsFunction);

调用 check() 会出现以下异常(在 Chrome 中测试):

NoSuchMethodError: method not found: 'typeof' (self.typeof is not a function)

使用dart:js:

import 'dart:js';

String check() => context.callMethod('typeof', [42]);

我得到异常:

NullError: method not found: 'apply' on null

将互操作函数调用包装在 try-catch 块中:

@JS()
external void someJsFunction(String input);

try {
  someJsFunction('hi');
} on NoSuchMethodError {
  // someJsFunction does not exist as a top level function
} catch(e) {
  if (e.toString() == 'property is not a function') {
    // We are in Dartium and someJsFunction does not exist as a top level function
  } else {
    rethrow;
  }
}

我假设前两种方法不起作用,因为 typeof 不是函数,而是运算符。第三种方法有效,但请注意我必须如何根据当前浏览器为不同的异常做准备。而且我不确定它是否适用于所有平台、所有浏览器。

有没有更好的方法在调用之前检查JS函数是否存在?

使用hasOwnProperty()

Every object descended from Object inherits the hasOwnProperty method. This method can be used to determine whether an object has the specified property as a direct property of that object; unlike the in operator, this method does not check down the object's prototype chain.

来自 MDN 网络文档 Object.prototype.hasOwnProperty()