JavaScript: Class Attribute

, , …,

Each JavaScript object has a attribute called “class”. The class attribute is a string. It is the second part of the string returned when you call Object.prototype.toString(obj). ECMAScript §8#sec-8.6.2

// showing the class attribute of a object
var xx = {3:4};
var cc = Object.prototype.toString(xx);
console.log(cc); // → [object Object]
// the string “Object” is the value of the class

User-defined object has a class value of "Object".

You can not set the class attribute.

Here's a function from David Flanagan's JavaScript Book that returns any object's class attribute.

// return a object's class attribute. Code from David Flanagan's JavaScript book
function classof(o) {
    if (o === null) return "Null";
    if (o === undefined) return "Undefined";
    return Object.prototype.toString.call(o).slice(8,-1);
}

console.log( classof(1) );      // Number

console.log( classof("") );     // String

console.log( classof(false) );  // Boolean

console.log( classof({}) );     // Object

console.log( classof([]) );     // Array

console.log( classof(/./) );    // RegExp

console.log( classof(new Date()) ); // Date

console.log( classof(function f() {}) ); // Function
blog comments powered by Disqus