[英]Javascript instanceof & typeof in GWT (JSNI)
我在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"
? instanceof
不應該,除非你從不同的窗口測試對象,因為從一個窗口的數組不是實例在你的例子返回false,所有的時間Array
不同的窗口的構造函數。
當你需要測試一個特定的東西並且你在一個窗口內操作時,使用instanceof
很棒(你必須要知道scunliffe指出的字符串原語與String對象的東西)。 請注意,您需要注意您的訂單,因為數組是Object
的instanceof
(以及Array
); 這適用於String
s和所有其他對象。
有一個替代方案沒有窗口問題,並且如果你正在進行調度,它可以很容易地用於switch
語句等:
function classify(arg) {
return Object.prototype.toString.call(arg);
}
這看起來很奇怪,但它的作用是使用Object
原型上的toString
函數,它具有已定義的行為(而不是使用您正在測試的實際對象可能具有的任何覆蓋,這可能具有不同的行為)。 所以給定這個功能:
function show(arg) {
alert(classify(arg));
}
你會得到這些結果:
show({}); // [object Object]
show("a"); // [object String]
show(new String("a")); // [object String]
show([]); // [object Array]
show(/n/); // [object RegExp]
show(function() { }); // [object Function]
並且無論您使用字符串原語還是String
實例,無論您正在測試的對象來自哪個窗口,您都將獲得這些結果。
由於其他一切似乎都得到了回答,讓我得到這個:
如何傳遞這些對象以便正確識別它們?
GWT會自動為字符串,整數等原始類型執行此操作。因此,您只需編寫:
public static native String test1()/ *-{
return "adfasdf";
}-*/;
public static native int test2()/ *-{
return 23;
}-*/;
有關其他注釋,請參閱文檔 。
對於數組,有一堆包裝類: JsArray
, JsArrayBoolean
, JsArrayInteger
, JsArrayNumber
, JsArrayString
。
public static native JsArrayString test3()/ *-{
return ['foo', 'bar', 'baz'];
}-*/;
你的測試函數總是返回false,因為你沒有提供一個return語句......並且String
在JavaScript中很有趣......如果你使用new String("asdf");
然后使用instanceof將工作,如果你只是用"asdf"
創建一個字符串,那么你將需要使用typeof。
function test(arg){
if (arg instanceof Array){
return 'Array';
} else if(arg instanceof String || typeof(arg) == 'String'){
return 'String';
} else if (arg instanceof Object){
return 'Object';
} else {
return typeof(arg);
}
}
(注意還有其他類型......日期,數字,自定義對象等)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.