isPrototypeOf&&getPrototypeOf

时间:2023-03-09 22:49:28
isPrototypeOf&&getPrototypeOf

在JavaScript这个一切皆为对象的世界里,难免会判断原型链的问题。那么我们就有必要了解了解isPrototypeOf和getPrototypeOf这两个方法咯。

1、isPrototypeOf

isPrototypeOf

作用

我的理解:确定一个对象的原型链中是否继承了prototype

官方语言:Determines whether an object exists in another object's prototype chain.

用法

prototype.isPrototypeOf(object)

备注

如果object的原型链中有prototype,则返回true;否则,返回false

我们一起demo下,看看isPrototypeOf到底是个什么东东。

<!DOCTYPE html>
<head>
<title>isPrototypeOf</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
</head>
<body>
<script>
function A(){ }
var a = new A();
//通过A创建一个对象a,所以a的__proto__是指向A.prototype的
console.log(A.prototype.isPrototypeOf(a));
//A.__proto__是指向Object.prototype的
console.log(Object.prototype.isPrototypeOf(A));
//由于A.prototype的__proto__是指向Object.prototype的,所以a也就含有Object.prototype咯
console.log(Object.prototype.isPrototypeOf(a)); </script>
</body>
</html>

运行上面的代码,截图chrome,如下

isPrototypeOf&&getPrototypeOf

从上面的代码和chrome结果,可知isPrototypeOf的确是判断对象中的原型链是否继承了prototype。

2、getPrototypeOf

getPrototypeOf

作用

返回对象__proto__指向的原型prototype

用法

Object的静态方法,使用如下Object.getPrototypeOf(object)

还是如此,我们一起demo下

<!DOCTYPE html>
<head>
<title>getPrototypeOf</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
</head>
<body>
<script>
function Fn(){ }
var fn = new Fn();
//通过getPrototypeOf静态方法,获得对象fn的prototype
var proto = Object.getPrototypeOf(fn);
//将获得的prototype添加一个name属性,并赋值
proto.name = 'Monkey';
//输出对象fn.name
console.log(fn.name);
//判断proto是否是Fn.prototype
console.log( 'proto === Fn.prototype? ' + (proto === Fn.prototype) );
//判断fn的__proto__是否指向了prototype
console.log( proto.isPrototypeOf(fn));
</script>
</body>
</html>

执行上面的代码,截图chrome,如下

isPrototypeOf&&getPrototypeOf

从上面的代码和结果图,可得:

getPrototypeOf,的确是返回对象__proto__指向的prototype。