Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When is a javascript function not an object?

I'm seeing the following behaviour, in the middle of a javascript debug session:

o // function (a1, a2, a3) {  return a1 + a2 + a3; }

typeof(o) //'function'

for (var n in o) { console.log(n); } //<a list of properties>

Object.keys(o) //TypeError: not an object

Object.prototype.toString.call(o); //"[object Function]"

which makes me wonder - can a function, ever not be object?

[running on Chrome 29, on a mac]


Note that this is in the middle of a very complex debug session. I don't exactly know where 'o' is coming from, or how it was created. Also, I've so far been unable to reproduce this issue with a simple test case. A simple setup works as expected:

var t = function() { return true; } //undefined
t.a = "aa" //"aa"
Object.keys(t) //["a"]
like image 414
blueberryfields Avatar asked Sep 17 '13 18:09

blueberryfields


People also ask

Is function considered an object in JavaScript?

In JavaScript, functions are first-class objects, because they can have properties and methods just like any other object. What distinguishes them from other objects is that functions can be called. In brief, they are Function objects. For more examples and explanations, see the JavaScript guide about functions.

What in JavaScript is not an object?

Nearly everything in JavaScript is an object other than six things that are not objects which are — null , undefined , strings, numbers, boolean, and symbols. These are called primitive values or primitive types.

Is not a function JavaScript object?

A TypeError: "x" is not a function occurs when a function is called on an object that does not contain the called function. When calling a built-in function that expects a callback function argument, which does not exist. When the called function is within a scope that is not accessible.

Is every function an object?

Every function is an object. Objects can contain functions (methods) but an object is not necessary a function.


1 Answers

When you see something like this, you might try:

console.log(Object.keys)

or equivalent.

(if you can find the original implementation of keys for your browser, to compare and make sure it's identical to what you're seeing)

(read the comments on the question for more ideas of things to look at if seeing this kind of problem)


False alarm. Functions are always objects, and the people at Chrome know how to make virtual machines.

I ran

grep -r "Object.defineProperty(" *

grep -r "Object.defineProperties(" *

and found a place where Object.keys is being overwritten, with a buggy function.

The related code was being loaded dynamically, so I didn't get to see it explicitly get loaded in the browser.

like image 89
blueberryfields Avatar answered Oct 04 '22 22:10

blueberryfields