Home Web Front-end JS Tutorial javascript instanceof 内部机制探析_javascript技巧

javascript instanceof 内部机制探析_javascript技巧

May 16, 2016 pm 06:18 PM
instanceof

比如:

复制代码 代码如下:

// 代码 1
function Pig() {}
var pig = new Pig();
alert(pig instanceof Pig); // => true

function FlyPig() {}
FlyPig.prototype = new Pig();
var flyPig = new FlyPig();
alert(flyPig instanceof Pig); // => true

来看另一段代码:
复制代码 代码如下:

// 代码 2
function Pig() { Pig.prototype = {/* some code */} }
var pig = new Pig();
alert(pig instanceof Pig); // => false

为何上面的猪 pig 不再是猪 Pig 了呢?
当一个对象是某个类的实例时,意味着这个对象具有该类的方法和属性。在 JavaScript 中,一个猪类的特性体现在原型中:
复制代码 代码如下:

// 代码 3
function Pig() {}
Pig.prototype = {
"吃猪食": function() {},
"睡觉": function() {},
"长膘": function() {}
};
var pig = new Pig();
alert(pig instanceof Pig); //=> true

如果动态改变了猪的特性,让猪变成了牛:
复制代码 代码如下:

// 代码 4
Pig.prototype = {
"吃草": function() {},
"犁田": function() {}
};
var niu= new Pig();
alert(pig instanceof Pig); //=> false
alert(niu instanceof Pig); //=> true

当未改变 Pig 的 prototype 时,猪还是猪,因此代码 3 中 pig 是 Pig 的实例。当改变 prototype 后,猪已经不是猪,而是披着猪皮的牛了。因此代码 4 中 pig 不再是 Pig 的实例,niu 反而是 Pig 的实例。

进一步分析前,先回顾一下 new 的内部机制。代码 2 中的 new Pig() 实际上等价为:
复制代码 代码如下:

// var pig = new Pig() 的等价伪代码:
var pig = (function() {
var o = {};
o.__proto__ = Pig.prototype; // line 2
Pig.call(o);
Pig.prototype = {/* some code */}; // line 4
return o; // line 5
})();

可以看出,在 line 2 时,o.__proto__ 指向了 Pig.prototype 指向的值。但在 line 4 时,Pig.prototype 指向了新值。也就是说,在 line 5 返回时,pig.__proto__ !== Pig.prototype. 正是这个变化,导致了代码 2 中的 pig 不是 Pig.

已经可以大胆推论出:instanceof 判断 pig 是不是 Pig 的依据是:看隐藏的 pig.__proto__ 属性是否等于 Pig.prototype !

为了进一步确认,我们可以在 Firefox 下模拟 instanceof 的内部实现代码:
复制代码 代码如下:

/**
* Gecko 引擎下,模拟 instanceof
*/
function _instanceof(obj, cls) {
// instanceof 的左操作数必须是非null对象或函数对象
if((typeof obj !== "object" || obj === null)
&& typeof obj !== "function") {
return false;
}

// instanceof 的右操作数必须是函数对象
if(typeof cls !== "function") {
throw new Error("invalid instanceof operand (" + cls + ")");
}

// 向上回溯判断
var p = obj.__proto__, cp = cls.prototype;
while(p) {
if(p === cp) return true;
p = p.__proto__;
}
return false;
}

测试页面:simulate-intanceof.html

最后考考大家:
复制代码 代码如下:

function Bird() {}
var bird = new Bird();
var o = {};
bird.__proto__ = o;
Bird.prototype = o;
alert(bird instanceof Bird); // true or false?
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What does instanceof do? What does instanceof do? Nov 14, 2023 pm 03:50 PM

The function of instanceof is to determine whether an object is an instance of a certain class, or whether it implements a certain interface. instanceof is an operator used to check whether an object is of a specified type. Usage scenarios of instanceof operator: 1. Type checking: can be used to determine the specific type of an object, so as to perform different logic according to different types; 2. Interface judgment: can be used to determine whether an object implements an interface, so as to determine whether an object implements an interface. The definition of the interface calls the corresponding method; 3. Downward transformation, etc.

How to use instanceof operator in java How to use instanceof operator in java May 19, 2023 am 08:16 AM

Concept 1. This operator is used to operate on objects and check whether the object is of a specific type (type or interface type). Format 2. If the object pointed to by the variable on the left side of the calculator is an object of the class or interface on the right side of the operator, the result is true. (Objectreferencevariable)instanceof(class/interfacetype) instance packagecom.verify_instanceof;publicclassTestInstanceOf{publicstaticvoidmain(String[]args){//The following four lines of code are used to prove: instanceof

What does instanceof mean in java What does instanceof mean in java Nov 13, 2023 pm 01:52 PM

In Java, instanceof is a binary operator used to check whether an object is an instance of a class or an instance of a subclass of a class. Its syntax is "object instanceof class", where object is an object Quote, class is a class name or interface name.

Why do we need to force transfer after instanceof? Why do we need to force transfer after instanceof? Nov 14, 2023 pm 03:43 PM

When using the instanceof operator to check the type of an object, if the result is true, it means that the object is an instance of the specified type. However, the compiler does not automatically convert the object to the specified type, so a cast is required. Casting is the operation of converting an object from one type to another. After using the instanceof operator, if you determine that the object is an instance of the specified type and want to operate with that type, you need to perform cast type conversion.

instanceof operator in Java instanceof operator in Java Sep 01, 2023 pm 08:01 PM

This operator is only used for object reference variables. This operator checks whether an object belongs to a specific type (class type or interface type). The instanceof operator is written as -(Objectreferencevariable)instanceof(class/interfacetype) If the object referenced by the variable on the left side of the operator passes the IS-A check of the class/interface type on the right side, the result will be true. Here is an example - Example Live Demonstration publicclassTest{ publicstaticvoidmain(Stringargs[]){&nbs

Why will an error be reported without adding instanceof? Why will an error be reported without adding instanceof? Nov 13, 2023 pm 03:05 PM

The reason is: The instanceof operator is used to check whether an object is an instance of a specific class (or its derived class). If the object is not an instance of a class, then type determination cannot be made and an error is thrown. To avoid this error, when using the instanceof operator, you need to ensure that the object is an instance of a class. If you are not sure about the type of an object, you can use other methods to determine the type.

Why not use instanceof Why not use instanceof Nov 14, 2023 pm 04:05 PM

The reasons for not using instanceof are: 1. The programming language you are using may not support the instanceof operator; 2. You think that using other methods can better achieve the requirements. In some cases, using other methods to check the object type may be more effective. or more suitable for your needs; 3. Not familiar with how the instanceof operator is used or unsure of its behavior; 4. In some cases, using "instanceof" may not be the best choice.

Why instanceof can interface Why instanceof can interface Nov 13, 2023 pm 03:09 PM

instanceof cannot be interfaced. The reason is: the instanceof keyword is used to check whether an object is an instance of a specific class, and cannot be directly used to check whether an object is an instance of an interface, because the interface cannot be instantiated.

See all articles