Home >Web Front-end >JS Tutorial >How Does the `new` Keyword Work in JavaScript to Create Objects and Implement Inheritance?
Exploring the 'new' Keyword in JavaScript
Understanding the 'new' Keyword
In JavaScript, the 'new' keyword plays a pivotal role in object creation and the concept of inheritance. Despite JavaScript's reputation as a non-object-oriented language, it introduces a unique approach to object-based programming through the 'new' keyword.
Purpose of the 'new' Keyword
The 'new' keyword has several key responsibilities:
Understanding [[prototype]] and 'prototype' Properties
Example of Object Creation with 'new'
function ObjMaker() { this.a = 'first'; } // 'ObjMaker' is the constructor function ObjMaker.prototype.b = 'second'; // 'ObjMaker.prototype' is the prototype object obj1 = new ObjMaker(); // 'new' creates a new 'obj1' object, assigns the prototype, and executes 'ObjMaker' obj1.a; // 'first' obj1.b; // 'second' // 'obj1' inherits 'b' from 'ObjMaker.prototype' while still accessing its own property 'a'
Hierarchy of Inheritance with 'new'
Through the 'new' keyword, JavaScript allows for a prototype-based inheritance model. By setting the [[prototype]] property, objects inherit properties and methods from their constructor's prototype. This enables the creation of subclasses that extend existing classes, like this:
function SubObjMaker() {} SubObjMaker.prototype = new ObjMaker(); // deprecated, use Object.create() now SubObjMaker.prototype.c = 'third'; obj2 = new SubObjMaker(); obj2.c; // 'third' obj2.b; // 'second' obj2.a; // 'first' // 'obj2' inherits 'c' from 'SubObjMaker.prototype', 'b' from 'ObjMaker.prototype', and 'a' from 'ObjMaker'
In summary, the 'new' keyword in JavaScript not only facilitates object creation but also enables a flexible inheritance mechanism that simulates class-based programming.
The above is the detailed content of How Does the `new` Keyword Work in JavaScript to Create Objects and Implement Inheritance?. For more information, please follow other related articles on the PHP Chinese website!