最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Optional Chaining - Function.prototype.apply was called on undefined, which is an undefined and not a function - St

programmeradmin0浏览0评论

Using optional chaining with function calls causes the expression to automatically return undefined instead of throwing an exception if the method isn't found.

Note: The code is using spread syntax, not rest parameters.

const fn1 = undefined
const args = []
const fn2 = () => {}
const fn3 = () => {}

console.log(fn1?.(...args, fn2, fn3))

Error:

console.log(fn1?.(...args, fn2, fn3))
                                ^
TypeError: Function.prototype.apply was called on undefined, which is an undefined and not a function

Using optional chaining with function calls causes the expression to automatically return undefined instead of throwing an exception if the method isn't found.

Note: The code is using spread syntax, not rest parameters.

const fn1 = undefined
const args = []
const fn2 = () => {}
const fn3 = () => {}

console.log(fn1?.(...args, fn2, fn3))

Error:

console.log(fn1?.(...args, fn2, fn3))
                                ^
TypeError: Function.prototype.apply was called on undefined, which is an undefined and not a function
Share Improve this question edited Mar 20, 2021 at 1:07 Wenfang Du asked Mar 13, 2021 at 2:46 Wenfang DuWenfang Du 11.5k13 gold badges76 silver badges114 bronze badges 4
  • 2 The problem appears only when ...args appears anywhere else other than the end in the function call. Weird. – maazadeeb Commented Mar 13, 2021 at 3:03
  • 1 It's weird that we get this error. Normally, you'ed get a "fn1 is not a function" error. This error shows up even when not using optional chaining. Compare: (() => { ({test: undefined}).test(...([])) })() // Uncaught TypeError: {(intermediate value)}.test is not a function vs (() => { ({test: undefined}).test(...([]), 1) })() // Uncaught TypeError: Function.prototype.apply was called on undefined, which is a undefined and not a function – Daniel Commented Mar 13, 2021 at 6:41
  • Looks like issue with chromium browsers, runs fine in Mozilla Firefox – Gowtham Raj J Commented Mar 13, 2021 at 6:46
  • 3 This is definitely a bug - their experimental implementation of the optional chaining does not work with how they transpile calls with spread syntax. – Bergi Commented Mar 13, 2021 at 14:39
Add a ment  | 

2 Answers 2

Reset to default 10

It turns out to be a V8 bug, I've submitted it there, hopefully, it'll be fixed soon.

Update: it has been fixed.

There are a couple rules to follow with ...rest arguments.

One of those rules is that the ...rest argument can only be the last argument.

foo(...one, ...wrong, ...wrong)
foo(...wrong, bad, bad)
foo(ok, ok, ...correct)

See:

https://developer.mozilla/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论