Paweł
Paweł

Reputation: 4526

Number.[property] is a property of object or constructor?

console.log(Number) //returns constructor function Number(), not an Object
console.log(Number.NaN) //returns the value of property NaN

Does it mean, that in Number.NaN the property NaN is a property of constructor function Number? I'm learning about objects and I thought that properties and methods are added by constructor function into objects.

thanks for any explanation!

Upvotes: 0

Views: 37

Answers (1)

Oriol
Oriol

Reputation: 288500

Note that, even if typeof says that something is a function instead of an object, functions are still objects. So you can add properties to it:

function f(){}
Object(f) === f; // true - belongs to Object type
f.prop = 'val';
f.prop; // 'val'

In this case, Number can be used as a function or as a constructor:

Number("123"); // 123 - used as a function, returns a primitive
new Number("123"); // Number {123} - used as a constructor, returns an object

If you look at it as a function, NaN is just a normal property.

If you look at it as a constructor, you can say that NaN is a static property. Static properties of a constructor are these that belong to the constructor instead of to the instances via prototypical inheritance.

class Foo {
  static func1() { return 1;}
  func2() { return 2; }
}
Foo.func1(); // 1 - static method
new Foo().func2(); // 2 - prototypical method

Upvotes: 1

Related Questions