Why does Illegal Invocation occur in JS?

Asked

Viewed 124 times

3

I’m using Gopherjs, and in it there are two ways to perform a function, via Call() or via Invoke(). Initially it was using a code similar to this:

js.Global.Get("navigator").Get("credentials").Get("store").Invoke(
    password.New(js.M{"id": id, "password": pass, "name": email}),
)

But it had as a result:

Uncaught (in Promise) Typeerror: Failed to execute 'store' on 'Credentialscontainer': Illegal Invocation at :1:36

So I decided to test the Call, using js.Global.Get("navigator").Get("credentials").Call("store", ...), that worked, but I was curious because the Invoke didn’t work.


In Javascript, it seems that you have a similar behavior if you do:

x = window.navigator.credentials.store; 
x(new PasswordCredential({id: "a", password:"b"}))

Or, yet to be done:

window.navigator.credentials.store.call(
    new PasswordCredential({id: "a", password:"b"})
)

In both cases it results in the error of Illegal invocation.


Why does this error occur? Because it only occurs with some functions/objects? There is a way to identify if there is a way to use the Invoke (or, the Call Javascript? ) before causing the error?

1 answer

1


In Go: store is the method, so we need to use Call. Invoke works only on functions. There is a difference, see below.

In JS: a method is not like a normal function because it has this. You can use a method as a function like this:

// Não funciona.
x = window.document.querySelector;
elem = x("a");
// Funciona, observe o bind().
x = window.document.querySelector.bind(window.document);
elem = x("a");
// Também funciona.
x = window.document.querySelector;
elem = x.call(window.document, "a");

Documentation links:

Browser other questions tagged

You are not signed in. Login or sign up in order to post.