]> git.kaiwu.me - njs.git/commitdiff
Improved Object.create().
authorArtem S. Povalyukhin <artem.povaluhin@gmail.com>
Thu, 28 Nov 2019 10:25:00 +0000 (13:25 +0300)
committerArtem S. Povalyukhin <artem.povaluhin@gmail.com>
Thu, 28 Nov 2019 10:25:00 +0000 (13:25 +0300)
This closes #261 issue on Github.

src/njs_object.c
src/test/njs_unit_test.c

index 592f6c9018fd49bad02377a9dec3ee255c84b9ab..38bcd8e0ba3ba0c8987e8c89e74123a836f1fadd 100644 (file)
@@ -28,6 +28,8 @@ static njs_int_t njs_object_enumerate_object(njs_vm_t *vm,
 static njs_int_t njs_object_own_enumerate_object(njs_vm_t *vm,
     const njs_object_t *object, const njs_object_t *parent, njs_array_t *items,
     njs_object_enum_t kind, njs_object_enum_type_t type, njs_bool_t all);
+static njs_int_t njs_object_define_properties(njs_vm_t *vm, njs_value_t *args,
+    njs_uint_t nargs, njs_index_t unused);
 
 
 njs_object_t *
@@ -250,13 +252,11 @@ njs_object_constructor(njs_vm_t *vm, njs_value_t *args, njs_uint_t nargs,
 }
 
 
-/* TODO: properties with attributes. */
-
 static njs_int_t
 njs_object_create(njs_vm_t *vm, njs_value_t *args, njs_uint_t nargs,
     njs_index_t unused)
 {
-    njs_value_t   *value;
+    njs_value_t   *value, *descs, arguments[3];
     njs_object_t  *object;
 
     value = njs_arg(args, nargs, 1);
@@ -278,6 +278,16 @@ njs_object_create(njs_vm_t *vm, njs_value_t *args, njs_uint_t nargs,
 
         njs_set_object(&vm->retval, object);
 
+        descs = njs_arg(args, nargs, 2);
+
+        if (njs_slow_path(!njs_is_undefined(descs))) {
+            arguments[0] = args[0];
+            arguments[1] = vm->retval;
+            arguments[2] = *descs;
+
+            return njs_object_define_properties(vm, arguments, 3, unused);
+        }
+
         return NJS_OK;
     }
 
index 873c5882cae223a5715f4d04b6580347a8b66d3c..95bfdbb52fc8b18e56ce7bb61a08427242443c0a 100644 (file)
@@ -10762,6 +10762,8 @@ static njs_unit_test_t  njs_test[] =
                  "o.__proto__ === p"),
       njs_str("true") },
 
+    /* Object.create() */
+
     { njs_str("var o = Object.create(Object.prototype);"
                  "o.__proto__ === Object.prototype"),
       njs_str("true") },
@@ -10775,6 +10777,15 @@ static njs_unit_test_t  njs_test[] =
     { njs_str("Object.create(1)"),
       njs_str("TypeError: prototype may only be an object or null: number") },
 
+    { njs_str("var o = Object.create(null, { a: { value: 1 } }); o.a"),
+      njs_str("1") },
+
+    { njs_str("var o = Object.create({ a: 0 }, { a: { value: 1 } }); o.a"),
+      njs_str("1") },
+
+    { njs_str("var o = Object.create({ get a() { return this.b; } }, { b: { value: 1 } }); o.a"),
+      njs_str("1") },
+
     { njs_str("var o = {a:1, b:2, c:3};"
                  "Object.keys(o)"),
       njs_str("a,b,c") },