惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

V
V2EX
L
LINUX DO - 热门话题
Engineering at Meta
Engineering at Meta
罗磊的独立博客
酷 壳 – CoolShell
酷 壳 – CoolShell
月光博客
月光博客
大猫的无限游戏
大猫的无限游戏
Attack and Defense Labs
Attack and Defense Labs
P
Privacy & Cybersecurity Law Blog
V
Visual Studio Blog
NISL@THU
NISL@THU
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
SecWiki News
SecWiki News
人人都是产品经理
人人都是产品经理
Jina AI
Jina AI
Last Week in AI
Last Week in AI
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
T
Threatpost
TaoSecurity Blog
TaoSecurity Blog
L
LINUX DO - 最新话题
量子位
Security Latest
Security Latest
博客园 - 司徒正美
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
I
Intezer
P
Privacy International News Feed
P
Palo Alto Networks Blog
爱范儿
爱范儿
有赞技术团队
有赞技术团队
Apple Machine Learning Research
Apple Machine Learning Research
Cloudbric
Cloudbric
P
Proofpoint News Feed
V
Vulnerabilities – Threatpost
阮一峰的网络日志
阮一峰的网络日志
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
博客园 - 三生石上(FineUI控件)
美团技术团队
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
雷峰网
雷峰网
Hugging Face - Blog
Hugging Face - Blog
Security Archives - TechRepublic
Security Archives - TechRepublic
The Cloudflare Blog
博客园_首页
博客园 - 聂微东
Hacker News - Newest:
Hacker News - Newest: "LLM"
S
Securelist
Spread Privacy
Spread Privacy
小众软件
小众软件
PCI Perspectives
PCI Perspectives
T
Troy Hunt's Blog

Dmitri Pavlutin Blog

Pure Functions in JavaScript: A Beginner's Guide Record Type in TypeScript: A Quick Intro How to Write Comments in React: The Good, the Bad and the Ugly 4 Ways to Create an Enum in JavaScript React forwardRef(): How to Pass Refs to Child Components TypeScript Function Types: A Beginner's Guide How to Use v-model to Access Input Values in Vue Mastering Vue refs: From Zero to Hero Environment Variables in JavaScript: process.env 5 Must-Know Differences Between ref() and reactive() in Vue How to Destructure Props in Vue (Composition API) Triangulation in Test-Driven Development How to Use nextTick() in Vue Programming to Interface Vs to Implementation A Smarter JavaScript Mapper: array.flatMap() Array Grouping in JavaScript: Object.groupBy() How to Access ES Module Metadata using import.meta JSON Modules in JavaScript How to Trim Strings in JavaScript TypeScript Function Overloading How to Debounce and Throttle Callbacks in Vue How to Show/Hide Elements in Vue Sparse vs Dense Arrays in JavaScript How to Fill an Array with Initial Values in JavaScript Covariance and Contravariance in TypeScript What are Higher-Order Functions in JavaScript? How to Use TypeScript with React Components Index Signatures in TypeScript How to Use React useReducer() Hook unknown vs any in TypeScript A Guide to React Context and useContext() Hook How to Use Promise.any() 2 Ways to Remove a Property from an Object in JavaScript 'return await promise' vs 'return promise' in JavaScript How to Use Promise.allSettled() How to Use fetch() with JSON JavaScript Promises: then(f,f) vs then(f).catch(f) What is a Promise in JavaScript? How to Use Promise.all() A Simple Guide to Component Props in React Don't Stop Me Now: How to Use React useTransition() hook A Simple Explanation of JavaScript Variables: const, let, var ES Modules Dynamic Import How to Memoize with React.useMemo() How to Cleanup Async Effects in React Why Math.max() Without Arguments Returns -Infinity How to Debounce and Throttle Callbacks in React Don't Confuse Function Expressions and Function Declarations in JavaScript How to Use ES Modules in Node.js Solving a Mystery Behavior of parseInt() in JavaScript How to Use Array Reduce Method in JavaScript 3 Ways to Merge Arrays in JavaScript A Guide to Jotai: the Minimalist React State Management Library The Difference Between Values and References in JavaScript How to Implement a Queue in JavaScript A Helpful Algorithm to Determine "this" value in JavaScript React useRef() Hook Explained in 3 Steps 7 Interview Questions on "this" keyword in JavaScript. Can You Answer Them? How to Greatly Enhance fetch() with the Decorator Pattern 7 Interview Questions on JavaScript Closures. Can You Answer Them? What's a Method in JavaScript? array.sort() Does Not Simply Sort Numbers in JavaScript How to Solve the Infinite Loop of React.useEffect() The New Array Method You'll Enjoy: array.at(index) What's the Difference between DOM Node and Element? Why Promises Are Faster Than setTimeout()? Everything About Callback Functions in JavaScript How React Updates State 5 Mistakes to Avoid When Using React Hooks 5 Best Practices to Write Quality JavaScript Variables Type checking in JavaScript: typeof and instanceof operators 3 Ways to Check if a Variable is Defined in JavaScript React Forms Tutorial: Access Input Values, Validate, Submit Forms Prototypal Inheritance in JavaScript How to Timeout a fetch() Request How to Learn JavaScript If You're a Beginner A Simple Explanation of React.useEffect() A Simple Explanation of JavaScript Iterators How to Use React Controlled Inputs Everything about null in JavaScript How to Use Fetch with async/await Getting Started with Arrow Functions in JavaScript An Interesting Explanation of async/await in JavaScript Front-end Architecture: Stable and Volatile Dependencies Is it Safe to Compare JavaScript Strings? How to Access Object's Keys, Values, and Entries in JavaScript What Actually is a String in JavaScript? 3 Ways to Shallow Clone Objects in JavaScript (w/ bonuses) Checking if an Array Contains a Value in JavaScript JavaScript Event Delegation: A Beginner's Guide How to Parse URL in JavaScript: hostname, pathname, query, hash 3 Ways to Detect an Array in JavaScript How to Get the Screen, Window, and Web Page Sizes in JavaScript 3 Ways to Check If an Object Has a Property/Key in JavaScript How to Compare Objects in JavaScript Object.is() vs Strict Equality Operator in JavaScript Own and Inherited Properties in JavaScript 5 Differences Between Arrow and Regular Functions How to Use Object Destructuring in JavaScript Your Guide to React.useCallback()
Inheritance in JavaScript: Understanding the constructor Property
Dmitri Pavlutin · 2016-05-01 · via Dmitri Pavlutin Blog

JavaScript has an interesting inheritance mechanism: prototypal. Most of the starting JavaScript developers have hard time understanding it, as well as I had.

All types in JavaScript (except the null and undefined values) have a constructor property, which is a part of the inheritance. For example:


var num = 150;

num.constructor === Number // => true

var obj = {};

obj.constructor === Object // => true

var reg = /\d/g;

reg.constructor === RegExp; // => true


In this article we'll dive into the constructor property of an object. It serves as a public identity of the class, which means it can be used for:

  • Identify to what class belongs an object (an alternative to instanceof)
  • Reference from an object or a prototype the constructor function
  • Get the class name

1. The constructor in primitive types

In JavaScript the primitive types are number, boolean, string, symbol (in ES6), null and undefined. Any value except null and undefined has a constructor property, which refers to the corresponding type function:

  • Number() for numbers: (1).constructor === Number
  • Boolean() for booleans: (true).constructor === Boolean
  • String() for strings: ('hello').constructor === String
  • Symbol() for symbols: Symbol().constructor === Symbol

The constructor property of a primitive can be used to determine it's type by comparing it with the corresponding function. For example to verify if the value is a number:


if (myVariable.constructor === Number) {

// code executed when myVariable is a number

myVariable += 1;

}


Notice that this approach is generally not recommended and typeof is preferable (see 1.1). But it can be useful for a switch statement, to reduce the number of if/else:


// myVariable = ...

var type;

switch (myVariable.constructor) {

case Number:

type = 'number';

break;

case Boolean:

type = 'boolean';

break;

case String:

type = 'string';

break;

case Symbol:

type = 'symbol';

break;

default:

type = 'unknown';

break;

}


1.1 The object wrapper for a primitive value

An object wrapper for a primitive is created when invoking the function with new operator. Wrappers can be created for new String('str'), new Number(15) and new Boolean(false) . It cannot be created for a Symbol, because invoked this way new Symbol('symbol') generates a TypeError.
The wrapper exists to allow developer to attach custom properties and methods to a primitive, because JavaScript doesn't allow for primitives to have own properties.

Existence of these objects may create confusion for determining the variable type based on the constructor, because the wrapper has the same constructor as the primitive:


var booleanObject = new Boolean(false);

booleanObject.constructor === Boolean // => true

var booleanPrimitive = false;

booleanPrimitive.constructor === Boolean // => true


2. The constructor in a prototype object

The constructor property in a prototype is automatically setup to reference the constructor function.


function Cat(name) {

this.name = name;

}

Cat.prototype.getName = function() {

return this.name;

}

Cat.prototype.clone = function() {

return new this.constructor(this.name);

}

Cat.prototype.constructor === Cat // => true


Because properties are inherited from the prototype, the constructor is available on the instance object too.


var catInstance = new Cat('Mew');

catInstance.constructor === Cat // => true


Even if the object is created from a literal, it inherits the constructor from Object.prototype.


var simpleObject = {

weekDay: 'Sunday'

};

simpleObject.prototype === Object // => true


2.1 Don't loose the constructor in the subclass

constructor is a regular non-enumerable property in the prototype object. It does not update automatically when a new object is created based on it. When creating a subclass, the correct constructor should be setup manually.

The following example creates a sublcass Tiger of the Cat superclass. Notice that initially Tiger.prototype still points to Cat constructor.


function Tiger(name) {

Cat.call(this, name);

}

Tiger.prototype = Object.create(Cat.prototype);

// The prototype has the wrong constructor

Tiger.prototype.constructor === Cat // => true

Tiger.prototype.constructor === Tiger // => false


Now if we clone a Tiger instance using clone() method defined on Cat.prototype, it will create a wrong Cat instance.


var tigerInstance = new Tiger('RrrMew');

var wrongTigerClone = tigerInstance.clone();

tigerInstance instanceof Tiger // => true

// Notice that wrongTigerClone is incorrectly a Cat instance

wrongTigerClone instanceof Tiger // => false

wrongTigerClone instanceof Cat // => true


It happens because Cat.prototype.clone() uses new this.constructor() to create a new clone. But the constructor still points to Cat function.

To fix this problem it's necessary to manually update the Tiger.prototype with the correct constructor function: Tiger. The clone() method will be fixed too.


//Fix the Tiger prototype constructor

Tiger.prototype.constructor = Tiger;

Tiger.prototype.constructor === Tiger // => true

var tigerInstance = new Tiger('RrrMew');

var correctTigerClone = tigerInstance.clone();

// Notice that correctTigerClone is correctly a Tiger instance

correctTigerClone instanceof Tiger // => true

correctTigerClone instanceof Cat // => true


Check this demo for a complete example.

3. An alternative to instanceof

object instanceof Class is used to determine if the object has the same prototype as the Class.
This operator searches in the prototype chain too, which sometimes makes difficult to identify the subclass instance from superclass instance. For example:


var tigerInstance = new Tiger('RrrMew');

tigerInstance instanceof Cat // => true

tigerInstance instanceof Tiger // => true


As seen in the example, it's not possible to check if tigerInstance is exactly a Cat or Tiger, because instanceof returns true in both cases.
This is where the constructor property shines, allowing to strictly determine the instance class.


tigerInstance.constructor === Cat // => false

tigerInstance.constructor === Tiger // => true

// or using switch

var type;

switch (tigerInstance.constructor) {

case Cat:

type = 'Cat';

break;

case Tiger:

type = 'Tiger';

break;

default:

type = 'unknown';

}

type // => 'Tiger'


4. Get the class name

The function object in JavaScript has a property name. It returns the name of the function or an empty string for anonymous one.
In addition with constructor property, this can be useful to determine the class name, as an alternative to Object.prototype.toString.call(objectInstance).


var reg = /\d+/;

reg.constructor.name // => 'RegExp'

Object.prototype.toString.call(reg) // => '[object RegExp]'

var myCat = new Cat('Sweet');

myCat.constructor.name // => 'Cat'

Object.prototype.toString.call(myCat) // => '[object Object]'


Because name returns an empty string for an anonymous function (however in ES6 the name can be inferred), this approach should be used carefully.

Conclusion

The constructor property is a piece of the inheritance mechanism in JavaScript. Precautions should be taken when creating hierarchies of classes.
However it offers nice alternatives to determine the type of an instance.

See also
Object.prototype.constructor
What's up with the constructor property in JavaScript?