Javascript: typeof says “function” but it can't be called as a function

混江龙づ霸主 提交于 2021-02-08 12:58:10

问题


I'm really puzzled with Javascript this time:

var x = Array.prototype.concat.call;
typeof x; // function
x(); // Uncaught TypeError: x is not a function

What on earth is going on here?


If it helps, I also noticed:

  • x([1,2],[3,4]) does not work either

  • toString also thinks it's a function:

    Object.prototype.toString.call(x); // "[object Function]"
    
  • This also happens with Array.prototype.concat.apply.

  • When it is forced as an expression it also does not work:

    (0, Array.prototype.concat.call)([1,2],[3,4]); // Same TypeError
    

Tested in Chrome and Node.


回答1:


The error is misleading. x is a function, but it has lost the referenced function (concat), which throws an error

Running on firefox gives a more descriptive error

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Called_on_incompatible_type

What it's saying is that the call function has nothing its bound to. In the same way that if you take an object like this:

const a = {
  b: 2,
  test() {
    console.log('hi', this.b);
  }
};
const c = a.test;
c();

You will get hi undefined as you've lost the relationship of the function to b.

You can fix this by either doing c.bind(a)() or c.call(a)

The call function behaves similarly. It is going to be the same for every function, and the pseudocode would look something like this:

class Function {
  constructor(functionDefinition) {
    this.functionDefinition = functionDefinition;
  }

  call(newThis, ...args) {
    // take this.functionDefinition, and call it with `this` and `args`
  }
}

Since you are extracting out the call function, it loses the function object it's associated with.

You can fix this by either binding concat to the function, or using call on call :-)

const a = []
const boundFn = a.concat.call.bind(a.concat)
console.log(boundFn([3], [1,2]));

// Or, you can use `call` to pass in the concat function
const callFn = a.concat.call;
console.log(callFn.call(a.concat, [4], [1,2]))


来源:https://stackoverflow.com/questions/50421102/javascript-typeof-says-function-but-it-cant-be-called-as-a-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!