代码之家  ›  专栏  ›  技术社区  ›  rafalry

GWT中的Javascript instanceof和typeof(JSNI)

  •  3
  • rafalry  · 技术社区  · 16 年前

    我在试图通过GWT中的JSNI使用一些对象时遇到了一个奇怪的问题。假设我们有一个定义了函数的javscript文件:

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

    我们想把这个函数称为user 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" ?
    3 回复  |  直到 16 年前
        1
  •  7
  •   T.J. Crowder    16 年前

    instanceof 在你的例子中不应该一直返回false 除非 您正在测试另一个窗口中的对象,因为一个窗口中的数组 不 一个例子 Array

    运算符 当你需要测试一个特定的东西,并且你在一个窗口中操作时,这是非常好的(你必须知道scunliffe指出的string原语和string对象的区别)。请注意,您需要注意您的顺序,因为数组是 Object (以及 数组 String 以及所有其他物体。

    switch

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

    这看起来很奇怪,但它所做的是使用 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]
    

    不管测试对象来自哪个窗口,也不管您使用的是字符串原语还是 字符串 实例。

        2
  •  1
  •   Igor Klimer    16 年前

    既然其他的问题似乎都得到了解决,那就让我来回答这个问题:

    如何传递这些对象以便正确识别它们?

    public static native String test1()/ *-{
       return "adfasdf";
    }-*/;
    
    public static native int test2()/ *-{
       return 23;
    }-*/;
    

    看到了吗 the docs 为了一些额外的笔记。

    对于数组,有一堆包装类: JsArray JsArrayBoolean , JsArrayInteger , JsArrayNumber JsArrayString .

    public static native JsArrayString test3()/ *-{
       return ['foo', 'bar', 'baz'];
    }-*/;
    
        3
  •  0
  •   scunliffe    16 年前

    String 在JavaScript中很有趣。。。如果你使用 new String("asdf"); 如果您只是用 "asdf"

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

    (注意还有其他类型。。。日期、编号、自定义对象等)