【发布时间】:2011-02-25 23:50:13
【问题描述】:
我在尝试通过 GWT 中的 JSNI 使用某些对象时遇到了一个奇怪的问题。假设我们有定义函数的 javscript 文件:
test.js:
function test(arg){
var type = typeof(arg);
if (arg instanceof Array)
alert('Array');
if (arg instanceof Object)
alert('Object');
if (arg instanceof String)
alert('String');
}
而我们要调用这个函数的用户JSNI:
public static native void testx()/ *-{
$wnd.test( new Array(1, 2, 3) );
$wnd.test( [ 1, 2, 3 ] );
$wnd.test( {val:1} );
$wnd.test( new String("Some text") );
}-*/;
问题是:
- 为什么
instanceof指令总是返回false? - 为什么
typeof总是返回"object"? - 如何传递这些对象以便正确识别它们?
【问题讨论】:
-
"string"(字符串字面量)和 new String("string")(String 对象)是有区别的。此外,任何不是文字的东西都是对象(IE 中的某些情况除外),所以对象测试应该排在最后,尤其是。如果你使用 return 语句。
-
感谢您的评论,$wnd.test(new String("Some text"));在这种情况下也是如此。
标签: javascript gwt types jsni