美文网首页
isPrototypeOf() 和 instanceof

isPrototypeOf() 和 instanceof

作者: Johnson23 | 来源:发表于2019-08-09 16:14 被阅读0次

Object.prototype.isPrototypeOf()

The isPrototypeOf() method checks if an object exists in another object's prototype chain.

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(Bar.prototype.isPrototypeOf(baz)); // true
console.log(Foo.prototype.isPrototypeOf(baz)); // true
console.log(Object.prototype.isPrototypeOf(baz)); // true

instanceof

The instanceof operator tests whether the prototype property of a constructor appears anywhere in the prototype chain of an object.

接着上面的例子

console.log(baz instanceof Baz); // true
console.log(baz instanceof Bar); // true
console.log(baz instanceof Foo); // true
console.log(baz instanceof Object); // true

console.log(Bar instanceof Foo) // false
console.log(Bar.prototype instanceof Foo) // true

相关文章

网友评论

      本文标题:isPrototypeOf() 和 instanceof

      本文链接:https://www.haomeiwen.com/subject/xuyhjctx.html