簡體   English   中英

如何檢查實例的構造函數

[英]how to check constructor of instance

我使用“ new”關鍵字創建了新實例(“ instance1”和“ instance2”)。 像這樣。

1. with'Child.prototype.constructor = Child'

function Parent() {

}

function Child() {
  Parent.call(this);
}

Child.prototype = new Parent();
Child.prototype.constructor = Child;

var instance1 = new Child();

2.沒有'Child.prototype.constructor = Child'

function Parent() {

}

function Child() {
  Parent.call(this);
}

Child.prototype = new Parent();

var instance2 = new Child();

我可以使用'instanceof'關鍵字檢查實例的構造函數。

instance1 instanceof Child  // true
instance1 instanceof Parent // true

這個結果是有道理的,因為我清楚地寫了'Child.prototype.constructor = Child;'。 因此instanceof關鍵字可以找到兩個構造函數。

instance2 instanceof Child  // true
instance2 instanceof Parent // true

但是這個結果對我來說沒有意義。 我期望

instance2 instanceof Child  // false

因為我沒有寫'Child.prototype.constructor = Child;'。

為什么???

instanceof運算符查找被測試對象的Prototype鏈( __proto__ )中是否存在Constructor.prototype對象。

因此,在您的示例中:

function Parent() {}

function Child() {
  Parent.call(this);
}

Child.prototype = new Parent();

var instance2 = new Child();    

由於instance2是從Child()構造函數構造的,因此instance2__proto__指向Child()構造函數的原型對象,即Child.prototype

當您測試:

instance2 instanceof Child

instanceof操作者會看如果Child.prototype對象存在於的原型鏈instance2 ,因為這會導致真正instance2從構造Child()的構造。
換一種說法:

instance2.__proto__ === Child.prototype


以第二種情況為例:

instance2 instanceof Parent

在這里, instance2的原型鏈(即( __proto__ ))也具有Parent.prototype對象,它將評估為true。

instance2.__proto__.__proto__ === Parent.prototype


最后說明:

instanceof運算符的工作原理非常類似於上述條件檢查,以測試對象是否為構造函數的實例。 constructor出現在構造函數的性質prototype對象從不使用instanceof而測試操作。

希望這可以幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM