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
558 views
in Technique[技术] by (71.8m points)

function - What does 'is an instance of' mean in Javascript?

The answer to this question: What is the initial value of a JavaScript function's prototype property?

has this sentence:

The initial value of prototype on any newly-created Function instance is a new instance of Object

As far as I know, Javascript doesn't have classes and the word 'instance' therefor doesn't make sense in my head. How should one interpret 'instance' in Javascript?

Sorry, I don't have enough rep to put my question in the comment thread on that answer.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

You're right that JavaScript doesn't have classes (yet), but it does have constructor functions, an instanceof operator that defines a relationship between objects and constructors, and a form of inheritance based on prototype chains.

obj instanceof ctor is true when ctor.prototype is on obj's prototype chain.

Modulo the caveat below, you could implement instanceof in EcmaScript 5 thus

function isInstanceOf(obj, ctor) {
  var proto = ctor.prototype;
  if (typeof obj === "object" || typeof obj === "function") {
    while (obj) {
      if (obj === proto) { return true; }
      obj = Object.getPrototypeOf(obj);
    }
  }
  return false;
}

Unless you go around reassigning prototypes (o = new MyConstructor(); MyConstructor.prototype = somethingElse) it should be the case that new MyConstructor() instanceof MyConstructor.

Section 15.3.5.3 explains this in detail.

15.3.5.3 [[HasInstance]] (V)

Assume F is a Function object.

When the [[HasInstance]] internal method of F is called with value V, the following steps are taken:

  1. If V is not an object, return false.

  2. Let O be the result of calling the [[Get]] internal method of F with property name "prototype".

  3. If Type(O) is not Object, throw a TypeError exception.

  4. Repeat

    1. Let V be the value of the [[Prototype]] internal property of V.
    2. If V is null, return false.
    3. If O and V refer to the same object, return true.

This isn't the whole story because host objects (like DOM nodes) are allowed to implement the [[HasInstance]] internal method however they like but most browsers implement host objects to behave as closely to native objects as possible.


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

...