TypeError: console.log(…) is not a function

匿名 (未验证) 提交于 2019-12-03 01:34:02

问题:

I'm really confused how I can get console.log is not a function on line 1091. If I remove the closure below, line 1091 doesn't complain such error. Chrome Version 43.0.2357.130 (64-bit).

Here is the code:

$scope.columnNameChanged = function (tableColumn) {     setDirtyColumn(tableColumn);     //propagate changes to the key fields     for (var i = 0; i 

回答1:

Solution

Simply put a semicolon (;) after console.log().


Explanation

The error is easily reproducible like this:

console.log() (function(){})

It’s trying to pass function(){} as an argument to the return value of console.log() which itself is not a function but actually undefined (check typeof console.log();). This is because JavaScript interprets this as console.log()(function(){}). console.log however is a function.

If you didn’t have the console object you’d see

ReferenceError: console is not defined

If you had the console object but not the log method you’d see

TypeError: console.log is not a function

What you have, however, is

TypeError: console.log(...) is not a function

Note the (...) after the function name. With those it’s referring to the return value of the function.


Respect the ;

All these code snippets result in all sorts of unexpected errors if no semicolons are present:

console.log() // As covered before () // TypeError: console.log(...) is not a function  console.log() // Accessing property 0 of property 1 of the return value… [1][0] // TypeError: console.log(...) is undefined  console.log() // Like undefined-3 -3 // NaN 

Another Example

You see the (...) oftentimes with the use of chained methods or chained property accessors:

string.match(/someRegEx/)[0] 

If that RegEx isn’t found, the method will return null and the property accessor on null will cause a TypeError: string.match(...) is nullreturn value is null. In the case of console.log(...) the return value was undefined.



回答2:

The error means that the return value of console.log() is not a function. You are missing a semicolon:

console.log('xxx', $scope.tableIndexes[i].columnName[j]); //                                                      ^ 

which makes the following (...) of the IIFE to be interpreted as a function call.


Compare the error messages of

> var foo = {bar: undefined}; > foo.bar(); Uncaught TypeError: foo.bar is not a function 

and

> var foo = {bar: function(){}}; > foo.bar()(); Uncaught TypeError: foo.bar(...) is not a function 


回答3:

One possible cause can be the declaration of var console somewhere in your script.

Use:

window.console.log(...); 

instead. Worked for me.

I hope it helps



回答4:

There is another way to encounter this error. console.log is not immutable and it is possible to accidentally overwrite the value.

console.log = 'hi'; 

In this case just reload the page to undo the damage.



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