]> git.kaiwu.me - njs.git/commitdiff
Object.prototype.isPrototypeOf() method.
authorDmitry Volyntsev <xeioex@nginx.com>
Fri, 9 Jun 2017 14:55:21 +0000 (17:55 +0300)
committerDmitry Volyntsev <xeioex@nginx.com>
Fri, 9 Jun 2017 14:55:21 +0000 (17:55 +0300)
njs/njs_object.c
njs/test/njs_unit_test.c

index 60fe0424360524a8a7a7cf8cabd04c91e2f148ce..d81f75cc0e79b9cb9788e96e741a9c572684bb42 100644 (file)
@@ -935,6 +935,36 @@ done:
 }
 
 
+static njs_ret_t
+njs_object_prototype_is_prototype_of(njs_vm_t *vm, njs_value_t *args,
+    nxt_uint_t nargs, njs_index_t unused)
+{
+    njs_object_t       *object, *proto;
+    const njs_value_t  *retval;
+
+    retval = &njs_string_false;
+
+    if (njs_is_object(&args[0]) && njs_is_object(&args[1])) {
+        proto = args[0].data.u.object;
+        object = args[1].data.u.object;
+
+        do {
+            object = object->__proto__;
+
+            if (object == proto) {
+                retval = &njs_string_true;
+                break;
+            }
+
+        } while (object != NULL);
+    }
+
+    vm->retval = *retval;
+
+    return NXT_OK;
+}
+
+
 static const njs_object_prop_t  njs_object_prototype_properties[] =
 {
     {
@@ -967,6 +997,13 @@ static const njs_object_prop_t  njs_object_prototype_properties[] =
         .value = njs_native_function(njs_object_prototype_has_own_property, 0,
                                      NJS_OBJECT_ARG, NJS_STRING_ARG),
     },
+
+    {
+        .type = NJS_METHOD,
+        .name = njs_string("isPrototypeOf"),
+        .value = njs_native_function(njs_object_prototype_is_prototype_of, 0,
+                                     NJS_OBJECT_ARG, NJS_OBJECT_ARG),
+    },
 };
 
 
index 7ab0e5c8f1f8c1600aa72e495b4d07ab432a0dd4..19473a822a33f15be3ea59c789608149b755bb7b 100644 (file)
@@ -5992,6 +5992,31 @@ static njs_unit_test_t  njs_test[] =
     { nxt_string("Object.getPrototypeOf('a')"),
       nxt_string("TypeError") },
 
+    { nxt_string("var p = {}; var o = Object.create(p);"
+                 "p.isPrototypeOf(o)"),
+      nxt_string("true") },
+
+    { nxt_string("var pp = {}; var p = Object.create(pp);"
+                 "var o = Object.create(p);"
+                 "pp.isPrototypeOf(o)"),
+      nxt_string("true") },
+
+    { nxt_string("var p = {}; var o = Object.create(p);"
+                 "o.isPrototypeOf(p)"),
+      nxt_string("false") },
+
+    { nxt_string("var p = {}; var o = Object.create(p);"
+                 "o.isPrototypeOf()"),
+      nxt_string("false") },
+
+    { nxt_string("var p = {}; var o = Object.create(p);"
+                 "o.isPrototypeOf(1)"),
+      nxt_string("false") },
+
+    { nxt_string("var p = {}; var o = Object.create(p);"
+                 "1..isPrototypeOf(p)"),
+      nxt_string("false") },
+
     { nxt_string("var d = new Date(''); d +' '+ d.getTime()"),
       nxt_string("Invalid Date NaN") },