dop251 / goja

ECMAScript/JavaScript engine in pure Go
MIT License
5.63k stars 378 forks source link

Check obj value before call ToObject to get prototype #576

Closed dvwzj closed 5 months ago

dvwzj commented 6 months ago

See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getPrototypeOf#return_value

In current state, If the obj is null it will throw an error when we call ToObject.

value.go#L425

func (n valueNull) ToObject(r *Runtime) *Object {
    r.typeErrorResult(true, "Cannot convert undefined or null to object")
    return nil
    //return r.newObject()
}

Instead of that, We just check the obj before to call ToObject to avoid the error.

builtin_object.go#L22

func (r *Runtime) object_getPrototypeOf(call FunctionCall) Value {
-    o := call.Argument(0).ToObject(r)
+    t := call.Argument(0)
+    if t == _null || t == _undefined {
+       return _null
+    }
+    o := t.ToObject(r)
     p := o.self.proto()
     if p == nil {
        return _null
     }
     return p
}
dop251 commented 5 months ago

The current implementation is according to ECMAScript standard, see https://tc39.es/ecma262/#sec-object.getprototypeof