一、代碼javascript
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>isPrototypeOf 與 instanceof區別</title>
</head>
<body>
<script type="text/javascript">
function Foo() {} function Bar() {} function Baz() {} Bar.prototype = Object.create(Foo.prototype); Baz.prototype = Object.create(Bar.prototype); var baz = new Baz(); console.log(Baz.prototype.isPrototypeOf(baz)); // true
console.log(baz instanceof Baz) // true
console.log(Bar.prototype.isPrototypeOf(baz)); // true
console.log(baz instanceof Bar) // true
console.log(Foo.prototype.isPrototypeOf(baz)); // true
console.log(baz instanceof Foo) // true
console.log(Object.prototype.isPrototypeOf(baz)); // true
console.log(baz instanceof Object) // true
</script>
</body>
</html>
二、區別html
isPrototypeOf()
方法用於測試一個對象是否存在於另外一個對象的原型鏈上。java
isPrototypeOf()
與 instanceof
運算符不一樣。在表達式 "object instanceof AFunction
"中,object
的原型鏈是針對 AFunction.prototype
進行檢查的,而不是針對 AFunction
自己。函數