Javascript instanceof & typeof in GWT (JSNI)

I ran into a curious problem trying to use some objects through JSNI in GWT. Let's say we have a javscript file with the specified function:

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');
}

And we want to call this function a JSNI user:

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") );
}-*/;

Questions:

  • why instanceofinstructions will always return false?
  • why typeofwill always return "object"?
  • How to transfer these objects so that they are correctly recognized?
+3
source share
3 answers

instanceof false , , Array .

instanceof , , ( String, scunliffe). , , - instanceof Object ( Array); String .

, switch , :

function classify(arg) {
    return Object.prototype.toString.call(arg);
}

, toString Object, ( , , , , -). , :

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.

+7

, , , :

, ?

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'];
}-*/;
+1

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);
  }
}

( , ... , , ..)

0

Source: https://habr.com/ru/post/1747848/


All Articles