Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
166 views
in Technique[技术] by (71.8m points)

JavaScript isPrototypeOf vs instanceof usage

Suppose we have the following:

function Super() {
      // init code
}

function Sub() {
      Super.call(this);
      // other init code
}

Sub.prototype = new Super();

var sub = new Sub();

Then, in some other part of our ocde, we can use either of the following to check for the relationship:

sub instanceof Super;   

or

Super.prototype.isPrototypeOf( sub )

Either way, we need to have both the object (sub), and the parent constructor (Super). So, is there any reason why you'd use one vs the other? Is there some other situation where the distinction is more clear?

I've already carefully read 2464426, but didn't find a specific enough answer.

question from:https://stackoverflow.com/questions/18343545/javascript-isprototypeof-vs-instanceof-usage

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Imagine you don't use constructors in your code, but instead use Object.create to generate objects with a particular prototype. Your program might be architected to use no constructors at all:

var superProto = {
    // some super properties
}

var subProto = Object.create(superProto);
subProto.someProp = 5;

var sub = Object.create(subProto);

console.log(superProto.isPrototypeOf(sub));  // true
console.log(sub instanceof superProto);      // TypeError

Here, you don't have a constructor function to use with instanceof. You can only use subProto.isPrototypeOf(sub).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...