javascript object class – How to get a JavaScript object’s class?

javascript object class methods are created with the same syntax as object methods. A JavaScript class is a blueprint for creating objects.

javascript object class

Use the keyword class to create a class. A class encapsulates data and functions that manipulate data.

javascript object class need getClass() for

  • typeof
  • instanceof
  • obj.constructor
  • func.prototype, proto.isPrototypeOf

Class basic syntax

class AllProduct {
  // class methods
  constructor() { ... }
  getSKU() { ... }
  getTitle() { ... }
  getDescription() { ... }
  ...
}

Then use new AllProduct() to create a new object with all the listed methods.

For example:

class User {

  constructor(name) {
    this.name = name;
  }

  sayHi() {
    alert(this.name);
  }

}

// Usage:
let user = new User("Mayur");
user.sayHi();

How to get a JavaScript object’s class?

examples

function Product() {}
var product = new Product();

typeof Product;             // == "function"
typeof product;             // == "object"

product instanceof Product;     // == true
product.constructor.name;   // == "Product"
Product.name                // == "Product"    

Product.prototype.isPrototypeOf(product);   // == true

Product.prototype.shop = function (x) {return x+x;};
product.shop(21);            // == 42

How to Get a Class Name of an Object?

function Func() {}
let func = new Func();
typeof Func; // == "function"
typeof fonc; // == "object"
console.log(typeof Func);
console.log(typeof func);

Example: JavaScript Objects

var first = { name:"Steve" }; // object literal syntax

var p2 = new Object(); // Object() constructor function
p2.name = "Steve"; // property

Don’t Miss : JavaScript Objects

Create Objects using Objects() Constructor

var member = new Object();

// Attach properties and methods to member object     
member.profileNm = "Virat";
member["nickNm"] = "Kohali"; 
member.age = 25;
member.getFullName = function () {
        return this.profileNm + ' ' + this.nickNm;
    };

Variables as Object Properties

var profileNm = "Virat";
var nickNm = "Kohali";

var member = { profileNm, nickNm }

Access JavaScript Object Properties & Methods

var member = { 
                profileNm: "Virat", 
                nickNm: "Kohali", 
                age: 25, 
                getFullName: function () { 
                    return this.profileNm + ' ' + this.nickNm 
                } 
            };

member.profileNm; // returns Virat
member.nickNm; // returns Kohali

member["profileNm"];// returns Virat
member["nickNm"];// returns Kohali

member.getFullName(); // calling getFullName function

I hope you get an idea about javascript object class.
I would like to have feedback on my infinityknow.com.
Your valuable feedback, question, or comments about this Article are always welcome.
If you enjoyed and liked this post, don’t forget to share.

Leave a Comment