有没有办法检查脚本是否在dart vm或dart2js中运行?

Tia*_*ago 6 dart dart2js

有没有办法检查脚本是否在dart vm或dart2js中运行?也许使用镜像API?

Lad*_*cek 8

据我所知,没有官方的方法.目的是,出于所有实际目的,您不必知道您是运行本机还是编译为JavaScript.

也就是说,你可以使用很少的黑客.最简单的一个可能利用的事实,飞镖有2种数字类型,int并且double,而JavaScript的只有一个,这相当于达特double和dart2js没有专门的执行int,只是还没有.因此,identical(1, 1.0)false在飞镖,以及VM实现了正常,但是当编译为JS,它是true.

请注意,在使用像这样的黑客之前你应该认真思考.在大多数情况下,您不必这样做,只需编写Dart并且不要尝试识别您是否正在运行JS.此外,没有人能保证它将永远有效.


Ced*_*edX 7

基于路径库中找到的代码片段(Dart v0.7.2):

import 'dart:mirrors';

/// Value indicating that the VM is Dart on server-side.
const int DART_SERVER=1;

/// Value indicating that the VM is Dart on client-side.
const int DART_CLIENT=2;

/// Value indicating that the VM is JavaScript on client-side (e.g. dart2js).
const int JS_CLIENT=3;

/// Returns the type of the current virtual machine.
int vmType() {
  Map<Uri, LibraryMirror> libraries=currentMirrorSystem().libraries;
  if(libraries[Uri.parse('dart:io')]!=null) return DART_SERVER;
  if(libraries[Uri.parse('dart:html')]!=null) return DART_CLIENT;
  return JS_CLIENT;
}

/// Application entry point.
void main() {
  print(vmType());
}
Run Code Online (Sandbox Code Playgroud)