Why does Illegal invocation occur in JS?

3

I'm using GopherJS, and there are two ways to execute a function, via Call() or via Invoke() . Initially I was using 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 turned out to be:

  

Uncaught (in promise) TypeError: Failed to execute 'store' on   'CredentialsContainer': Illegal invocation       at: 1: 36

So I decided to test Call , using js.Global.Get("navigator").Get("credentials").Call("store", ...) , this worked, but I was curious because Invoke did not work.

In Javascript, it looks like it behaves similarly if you do:

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

Or, if you do:

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? Why does it only occur with some functions / objects? Is there a way to identify whether there is a way to use Invoke (or, Call of Javascript?) Before causing the error?

    
asked by anonymous 19.11.2018 / 19:18

1 answer

1

In Go: store is the method, so we need to use Call . Invoke works only in 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:

19.11.2018 / 22:18