DEV Community

rounakcodes
rounakcodes

Posted on

1 1

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.

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

Top comments (0)