How to Implement the instanceof in Javascript?

  • 时间:2020-09-17 14:37:27
  • 分类:网络文摘
  • 阅读:95 次
JS How to Implement the instanceof in Javascript? javascript

NodeJs / Javascript

In Javascript, the operator instanceof is used to perform a test to check if the prototype property of a constructor apperas in the chain of the object’s prototype chain.

The syntax to use is:

1
2
3
object instanceof constructor
// object - the object to test
// constructor - to test against
object instanceof constructor
// object - the object to test
// constructor - to test against

For example:

1
2
3
4
5
6
7
8
9
10
function Car() {}
function Train() {}
 
const car = new Car();
const train = new Train();
 
console.log(car instanceof Car); // true
console.log(car instanceof Train); // false
console.log(train instanceof Car); // false;
console.log(train instanceof Train); // true;
function Car() {}
function Train() {}

const car = new Car();
const train = new Train();

console.log(car instanceof Car); // true
console.log(car instanceof Train); // false
console.log(train instanceof Car); // false;
console.log(train instanceof Train); // true;

We can implement a instanceOf function in pure Javascript that does the same instanceof check – probably useful in front-end Javascript interview:

1
2
3
4
5
6
7
8
9
function instanceOf(left, right) {
    let proto = left.__proto__;
    let prototype = right.prototype;
    for (;;) {
        if (proto === null) return false;
        if (proto === prototype) return true;
        proto = proto.__proto__; // trace way up along the chain
    }
}
function instanceOf(left, right) {
    let proto = left.__proto__;
    let prototype = right.prototype;
    for (;;) {
        if (proto === null) return false;
        if (proto === prototype) return true;
        proto = proto.__proto__; // trace way up along the chain
    }
}

And it expects to produce the same results:

1
2
3
4
console.log(instanceOf(car, Car)); // true
console.log(instanceOf(car, Train)); // false
console.log(instanceOf(train, Car)); // false;
console.log(instanceOf(train, Train)); // true;
console.log(instanceOf(car, Car)); // true
console.log(instanceOf(car, Train)); // false
console.log(instanceOf(train, Car)); // false;
console.log(instanceOf(train, Train)); // true;

The idea is conduct a loop, and trace up the prototype property along the chain until we have a match (equal prototype in the chain) or we have reached the end of the chain – which is null.

–EOF (The Ultimate Computing & Technology Blog) —

推荐阅读:
“最大份扬州炒饭”喂猪背后的浮躁心态  吉尼斯宣布“最大份扬州炒饭”纪录无效  包菜有意想不到的防癌养胃保健功效  食药总局公布不合格食品名单蜂蜜上黑榜  板栗养胃健脾是医药学家推崇的补肾果  冬季手脚冰凉者可以多喝“三红”暖身汤  老百姓对于食物中致癌物的认识误区  三类食品是引发癌症(恶性肿瘤)的因素  枸杞虽好但两种人吃了反而对健康有害  4个与大豆营养价值有关的真假说法 
评论列表
添加评论