From 193c1ae9cf860dc8db9c1d2c252478d504efa511 Mon Sep 17 00:00:00 2001 From: yangjin Date: Thu, 14 Nov 2019 00:17:48 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E6=B7=BB=E5=8A=A0=E5=AE=9E=E7=8E=B0=20?= =?UTF-8?q?instanceof=20=E7=AC=94=E8=AE=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../\345\256\236\347\216\260instanceof.md" | 39 +++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git "a/docs/javaScript/\345\256\236\347\216\260instanceof.md" "b/docs/javaScript/\345\256\236\347\216\260instanceof.md" index e69de29b..ead2b937 100644 --- "a/docs/javaScript/\345\256\236\347\216\260instanceof.md" +++ "b/docs/javaScript/\345\256\236\347\216\260instanceof.md" @@ -0,0 +1,39 @@ +# 实现 instanceof + +`instanceof` 用于判断构造函数的 `prototype` 属性是否出现在一个对象的原型链中。 + +```js +function Car(make, model, year) { + this.make = make; + this.model = model; + this.year = year; +} +var auto = new Car('Honda', 'Accord', 1998); +console.log(auto instanceof Car); // true +console.log(auto instanceof Object); // true +``` +## instanceof + +```js +/** + * instanceof + * + * @param {Object} obj 需要判断的对象. + * @param {Function} ctor 构造函数. + * @returns {Boolean} 返回判断结果. + */ +function instanceof(obj, ctor) { + var proto = obj.__proto__; + var prototype = ctor.prototype; + while (true) { + if (proto == null) return false; + if (proto == prototype) return true; + proto = proto.__proto__; + } +} +``` + +## 参考 + +- [instanceof](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/instanceof) +- [instanceof原理](https://juejin.im/post/5b7f64be51882542c83476f0) \ No newline at end of file