gpt4 book ai didi

dart - 如何使用新的js 0.6.0包将Dart类映射到JS “class”?

转载 作者:行者123 更新时间:2023-12-03 02:53:44 27 4
gpt4 key购买 nike

index.html

<!doctype html>
<html>
<head>
</head>
<script>
var Apple = function(type) {
this.type = type;
this.color = "red";
};

Apple.prototype.getInfo = function() {
return this.color + ' ' + this.type + ' apple';
};
</script>
<body>
<script type="application/dart" src="index.dart"></script>
<script src="packages/browser/dart.js"></script>
</body>
</html>

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

main() {
// this works fine
var apple = new js.JsObject(js.context['Apple'], ['Macintosh']);
print(apple.callMethod('getInfo', []));
print(new Apple().getInfo());
}

@Js() // about to being changed to @JS
class Apple {
external String get type;
external set type(String type);
external String get color;
external set color(String color);
external factory Apple(String type);
}

只需添加 @Js()注释结果即可

Exception: 'dart:js': Failed assertion: line 393: 'p.isNamed' is not true. Observatory listening at http://127.0.0.1:35293/ Internal error: Dart_Invoke expects library argument 'target' to be loaded.



更新
删除 external factory Apple(String type);可修复该异常。

现在我明白了

Observatory listening at http://127.0.0.1:38029/
red Macintosh apple
Exception: Class 'Apple' has no instance method 'getInfo'.

NoSuchMethodError: method not found: 'getInfo'
Receiver: Instance of 'Apple'
Arguments: [...]
Apple.getInfo
main

最佳答案

该类需要构造函数,但没有factory
这个JS

<script>
var Apple = function(type) {
this.type = type;
this.color = "red";
this.getInfo2 = function() {
return this.color + ' ' + this.type + ' apple';
};
};

Apple.prototype.getInfo = function() {
return this.color + ' ' + this.type + ' apple';
};
</script>

和这个Dart代码
main() {
var apple = new js.JsObject(js.context['Apple'], ['Macintosh']);
print(apple.callMethod('getInfo', []));
print(new Apple('Macintosh').type);
print(new Apple('Macintosh').getInfo2());
print(new Apple('Macintosh').getInfo());
}

@Js() // about to being changed to @JS
class Apple {
external String get type;
external set type(String type);
external String get color;
external set color(String color);
external String getInfo();
external String getInfo2();
external Apple(String type);
}

它按预期工作。

关于dart - 如何使用新的js 0.6.0包将Dart类映射到JS “class”?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33168767/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com