When we say "instance of", we assume that we are dealing with an object. Why JavaScript's operator instanceof
returns true
when we ask (class A { }) instanceof Function
, but typeof (class A { }) == "function"
? Why not object
?
When we say "instance of", we assume that we are dealing with an object. Why JavaScript's operator instanceof
returns true
when we ask (class A { }) instanceof Function
, but typeof (class A { }) == "function"
? Why not object
?
- You are dealing with an object. Functions are objects in Javascript. – AmericanUmlaut Commented Feb 7, 2017 at 21:51
- 1 Why is it surprising that an instance of a function has a type of "function"? Seems to me like it would be an important type distinction. – user1106925 Commented Feb 7, 2017 at 21:51
-
2
@ktretyak The syntax is extremely misleading in what
class
actually does. This is one reason why I don't like using it. JavaScript never has, and still does not have class-based object-oriented programming. – castletheperson Commented Feb 7, 2017 at 22:00 - 1 The syntax is really only misleading if you assume the semantics of other languages, which is never a wise move. – user1106925 Commented Feb 7, 2017 at 22:28
-
1
@4castle: Maybe you feel less negative about classes if you think about syntax being a way of expressing intent. And hopefully a language evolves to make it easier to express intent. You could also consider array literals to be misleading, since they actually create objects. But it expresses the intent better than using an object literal (plus other goodies, like
length
). Or think about IIFEs vslet
. It might just be a matter of time to get used to new things and properly place them in your mental model of the language (that was the case for me at least). – Felix Kling Commented Feb 7, 2017 at 22:40
1 Answer
Reset to default 7Why JavaScript's operator
instanceof
returns true when we ask(class A { }) instanceof Function
class
es are just syntactic sugar for constructor functions. I.e. the evaluation of class A {}
produces a function.
The following two examples are (more or less) equivalent, i.e. they produce the same result/value:
// class
class A {
constructor() {
this.foo = 42;
}
bar() {
console.log(this.foo);
}
}
// constructor function
function A() {
this.foo = 42;
}
A.prototype.bar = function() {
console.log(this.foo);
}
Everything that is not a primitive value (string, number, boolean, null, undefined, symbol) is an object in JavaScript. Functions are objects too, with special internal properties that makes them callable (and/or constructable).
Why not object?
typeof
returns the string "function"
for function values because that's how it is defined in the specification.