JavaScript: The Definitive Guide, Sixth Editio javaScript权威指南(第6版) pdf 文字版-文字版, javascript电子书, 和javascript 有关的电子书:

9.5.1 The instanceof operator

9.5.1 The instanceof operator

The instanceof operator was described in §4.9.4 . The left-hand operand should be the object whose class is being tested, and the right-hand operand should be a constructor function that names a class. The expression o instanceof cevaluates to trueif oinherits from c.prototype. The inheritance need not be direct. If o inherits from an object that inherits from an object that inherits from c.prototype, the expression will still evaluate to true.

As noted earlier in this chapter, constructors act as the public identity of classes, but prototypes are the fundamental identity. Despite the use of a constructor function with instanceof, this operator is really testing what an object inherits from, not what constructor was used to create it.

If you want to test the prototype chain of an object for a specific prototype object and do not want to use the constructor function as an intermediary, you can use the isPrototypeOf()method. For example, we could test whether an object rwas a member of the range class defined in Example 9-1 with this code:

range.methods.isPrototypeOf(r); // range.methods is the prototype object.

One shortcoming of the instanceof operator and the isPrototypeOf() method is that they do not allow us to query the class of an object, only to test an object against a class we specify. A more serious shortcoming arises in client-side JavaScript where a web application uses more than one window or frame. Each window or frame is a distinct execution context, and each has its own global object and its own set of constructor functions. Two arrays created in two different frames inherit from two identical but distinct prototype objects, and an array created in one frame is not instanceof the Array() constructor of another frame.

友情链接It题库(| 版权归yishouce.com所有| 友链等可联系|粤ICP备16001685号-1