我在GWT中嘗試通過JSNI使用某些對象時遇到了一個奇怪的問題。比方說,我們有一個函數javscript文件中定義:在GWT中使用Javascript instanceof&typeof(JSNI)
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語句。 – Dormilich 2010-05-31 13:35:10
感謝您的評論,$ wnd.test(new String(「Some text」));在這種情況下也是一樣。 – rafalry 2010-05-31 14:09:45