Skip to content

JavaScript class type

  • by

A JavaScript class is a type of function. Classes are declared with the class keyword.

function expression syntax

// Initializing a function with a function expression
const x = function() {}

class expression syntax

// Initializing a class with a class expression
const y = class {}

JavaScript class type

Classes Are Functions

We can access [[Prototype]] of an object using the Object.getPrototypeOf() method. Let’s use that to test the empty function we created.

Object.getPrototypeOf(x);

We can also use that method in the class we just created.

Object.getPrototypeOf(y);

The code declared with function and class both return a function [[Prototype]]

ƒ () { [native code] }

The code declared with function and class both return a function [[Prototype]]. With prototypes, any function can become a constructor instance using the new keyword.

const x = function() {}

// Initialize a constructor from a function
const constructorFromFunction = new x();

console.log(constructorFromFunction);

Output:

x {}
constructor: ƒ ()

This applies to classes as well.

const y = class {}

// Initialize a constructor from a class
const constructorFromClass = new y();

console.log(constructorFromClass);

Output:

y {}
constructor: class

Defining a Class

constructor.js

// Initializing a constructor function
function Hero(name, level) {
	this.name = name;
	this.level = level;
}

class.js

// Initializing a class definition
class Hero {
	constructor(name, level) {
		this.name = name;
		this.level = level;
	}
}

Source: https://www.digitalocean.com/

How to get a JavaScript object’s class?

Answer: Depending on what you need getClass() for, there are several options in JavaScript:

A few examples:

function Foo() {}
var foo = new Foo();

typeof Foo;             // == "function"
typeof foo;             // == "object"

foo instanceof Foo;     // == true
foo.constructor.name;   // == "Foo"
Foo.name                // == "Foo"    

Foo.prototype.isPrototypeOf(foo);   // == true

Foo.prototype.bar = function (x) {return x+x;};
foo.bar(21);            // == 42

Note: if you are compiling your code with Uglify it will change non-global class names. To prevent this, Uglify has a --mangle param that you can set to false using gulp or grunt.

Source: stackoverflow.com

Do comment if you have any doubts or suggestions on this Js class topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published. Required fields are marked *