LibJS: Implement Object.prototype.isPrototypeOf

Spec: https://tc39.es/ecma262/#sec-object.prototype.isprototypeof
This commit is contained in:
Luke 2020-12-28 01:22:38 +00:00 committed by Andreas Kling
parent ee1d9217aa
commit be30dc2b18
Notes: sideshowbarker 2024-07-19 00:30:06 +09:00
4 changed files with 40 additions and 0 deletions

View file

@ -149,6 +149,7 @@ namespace JS {
P(isFinite) \
P(isInteger) \
P(isNaN) \
P(isPrototypeOf) \
P(isSafeInteger) \
P(isView) \
P(join) \

View file

@ -50,6 +50,7 @@ void ObjectPrototype::initialize(GlobalObject& global_object)
define_native_function(vm.names.toLocaleString, to_locale_string, 0, attr);
define_native_function(vm.names.valueOf, value_of, 0, attr);
define_native_function(vm.names.propertyIsEnumerable, property_is_enumerable, 1, attr);
define_native_function(vm.names.isPrototypeOf, is_prototype_of, 1, attr);
}
ObjectPrototype::~ObjectPrototype()
@ -138,4 +139,23 @@ JS_DEFINE_NATIVE_FUNCTION(ObjectPrototype::property_is_enumerable)
return Value(property_descriptor.value().attributes.is_enumerable());
}
JS_DEFINE_NATIVE_FUNCTION(ObjectPrototype::is_prototype_of)
{
auto object_argument = vm.argument(0);
if (!object_argument.is_object())
return Value(false);
auto* object = &object_argument.as_object();
auto* this_object = vm.this_value(global_object).to_object(global_object);
if (!this_object)
return {};
for (;;) {
object = object->prototype();
if (!object)
return Value(false);
if (same_value(this_object, object))
return Value(true);
}
}
}

View file

@ -46,6 +46,7 @@ private:
JS_DECLARE_NATIVE_FUNCTION(to_locale_string);
JS_DECLARE_NATIVE_FUNCTION(value_of);
JS_DECLARE_NATIVE_FUNCTION(property_is_enumerable);
JS_DECLARE_NATIVE_FUNCTION(is_prototype_of);
};
}

View file

@ -0,0 +1,18 @@
test("basic functionality", () => {
function A() {}
function B() {}
A.prototype = new B();
const C = new A();
expect(A.prototype.isPrototypeOf(C)).toBeTrue();
expect(B.prototype.isPrototypeOf(C)).toBeTrue();
expect(A.isPrototypeOf(C)).toBeFalse();
expect(B.isPrototypeOf(C)).toBeFalse();
const D = new Object();
expect(Object.prototype.isPrototypeOf(D)).toBeTrue();
expect(Function.prototype.isPrototypeOf(D.toString)).toBeTrue();
expect(Array.prototype.isPrototypeOf([])).toBeTrue();
});