日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

手動實現function isInstanceOf(child,Parent)

作者:翼遙bingo 更新時間: 2022-07-10 編程語言

文章目錄

    • 1-1 instance主要作用及使用
    • 1-2 insInstanceOf原理
    • 1-3 手擼代碼及測試階段

1-1 instance主要作用及使用

判斷一個實例是否屬于某種類型

let person = function(){
}
let no = new person();
no instanceof person;    // true

1-2 insInstanceOf原理

在了解原理及手擼代碼之前,需要了解JS原型鏈: 

JS原型鏈

1、 主要實現原理: 只要右邊變量的prototype在左邊變量的原型鏈上即可

  • so,instanceof在查找的過程中會遍歷左邊變量的原型鏈,直到找到右邊變量的prototype
  • 查找失敗,返回false,即左邊變量并非右邊變量的實例

2、

function new_instanceOf(leftValue, rightValue) {
	let rightValue = rightValue.prototype;      // 取右表達式的prototyoe值
	leftValue = leftValue.__proto__;
	while (true) {
		if  (leftValue === rightProto) {
			return true;
		} 
		if (leftValue === null) {
   		return false;
   	}
		leftVaule = leftVaule.__proto__ ;
	}
}

1-3 手擼代碼及測試階段

function instance_of(l,r) {
	let rProto = r.prototype;
	let lValue = l.__proto__;
	while(true) {
		if (lValue === null) {
			return false;
		}
		if (lValue === rProto) {
			return true;
		}
		lValue = lValue.__proto__;
	}
}
// 開始測試
var a = []
var b = {}

function Foo(){}
var c = new Foo()
function child(){}
function father(){}
child.prototype = new father() 
var d = new child()

console.log(instance_of(a, Array)) // true
console.log(instance_of(b, Object)) // true
console.log(instance_of(b, Array)) // false
console.log(instance_of(a, Object)) // true
console.log(instance_of(c, Foo)) // true
console.log(instance_of(d, child)) // true
console.log(instance_of(d, father)) // true

在這里插入圖片描述


原文鏈接:https://blog.csdn.net/hannah2233/article/details/125481680

欄目分類
最近更新