[go: up one dir, main page]

DEV Community

rounakcodes
rounakcodes

Posted on

revisiting functions (not prototypes) 🤥

Some notes for quick revision

a function with a custom property

function aFunction() {
  this.someKey = "someValue";
}
aFunction.customKey = "customValue"
Enter fullscreen mode Exit fullscreen mode

this is a runtime binding in most cases, so someKey is not a property of aFunction or aFunction.prototype.

Image description

The prefix custom was chosen to distinguish from the default properties present on the function like name, caller etc. (Should it have been called own? Prototypical hangover! 🥱)
The pair of customKey and customValue will be referred to as custom property for the purposes of this document.

Image description

Since the constructor is a function, it also has a prototype and the recursion continues forever. Remember that the [[Prototype]] property is only a link, not an actual copy of any object.

Note that the custom property is available on the constructor but not on the prototype.

instance

let aInstance = new aFunction()
console.log(aInstance)
Enter fullscreen mode Exit fullscreen mode

Image description

The custom property of aFunction is not present on the [[Prototype]] of aInstance because the [[Prototype]] of aInstance is aFunction.prototype.

prototype

  • Except for when we talk about the prototype property on a function, we always mean the internal property [[Prototype]] when we say prototype.
  • The internal property [[Prototype]] represents a link to some properties, not a copy of those properties
  • Every prototype (accessed using Object.getPrototypeOf()) has a constructor property and a [[Prototype]] property.
  • Since [[Prototype]] of aInstance is the value of aFunction.prototype, the [[Prototype]] of aInstance is said to be aFunction.prototype.
  • Similarly, the [[Prototype]] of aFunction is said to Object.prototype

custom property

  • The custom property is like the common Object properties: Object.create, Object.assign, Object.getPrototypeOf etc. They are not meant to be called on object instances.
  • On the contrary, the common Array properties like map, slice, push etc are found on the [[Prototype]] of an array instance because they are meant to be used with an instance not on the parent Array object

constructor property

Note that the constructor property of an instance can be changed using aInstance.constructor = and of the parent using Object.getPrototypeOf(aInstance).constructor. So, use instanceof operator instead of checking the constructor of an instance.

Top comments (0)