How to use custom types to implement a custom instanceof in JavaScript

3 Answers

0 votes
// Custom type that controls how instanceof behaves
class Employee {
    constructor(name, employeeId) {
        this.name = name;
        this.employeeId = employeeId;
    }

    // Custom instanceof logic
    static [Symbol.hasInstance](obj) {
        return (
            obj !== null &&
            typeof obj === "object" &&
            typeof obj.employeeId === "number"
        );
    }
}

// Helper function
function isEmployee(value) {
    return value instanceof Employee;
}

// Test objects
const emp1 = new Employee("Alice", 1001);

const emp2 = {
    name: "Bob",
    employeeId: 2002
};

const randomObj = {
    name: "Break Fest"
};

// Tests
console.log(emp1 instanceof Employee);      // true
console.log(emp2 instanceof Employee);      // true
console.log(randomObj instanceof Employee); // false

console.log(isEmployee(emp1));      // true
console.log(isEmployee(emp2));      // true
console.log(isEmployee(randomObj)); // false


/*
run:

true
true
false
true
true
false

*/

 



answered 14 hours ago by avibootz
0 votes
// Custom type that controls how instanceof behaves
class Employee {
    constructor(name, employeeId) {
        this.name = name;
        this.employeeId = employeeId;
    }

    // Custom instanceof logic
    static [Symbol.hasInstance](obj) {
        return (
            obj !== null &&
            typeof obj === "object" &&
            typeof obj.employeeId === "number"
        );
    }
}

// Helper function
function isEmployee(value) {
    return value instanceof Employee;
}

// Test objects
const emp1 = new Employee("Alice", 1001);

const emp2 = {
    name: "Zig",
    employeeId: 2014
};

const randomObj = {
    name: "Break Fest"
};

// Tests
console.log(emp1 instanceof Employee);      // true
console.log(emp2 instanceof Employee);      // true
console.log(randomObj instanceof Employee); // false

console.log(isEmployee(emp1));      // true
console.log(isEmployee(emp2));      // true
console.log(isEmployee(randomObj)); // false


/*
run:

true
true
false
true
true
false

*/

 



answered 13 hours ago by avibootz
0 votes
class Employee {
    constructor(name) {
        this.name = name;
    }
}

function isEmployee(value) {
    return value instanceof Employee;
}

const emp = new Employee("Alice");
const obj = { name: "Wonderland" };

console.log(isEmployee(emp)); // true
console.log(isEmployee(obj)); // false


/*
run:

true
false

*/

 



answered 13 hours ago by avibootz
...