簡體   English   中英

JavaScript isPrototypeOf vs instanceof用法

[英]JavaScript isPrototypeOf vs instanceof usage

假設我們有以下內容:

function Super() {
      // init code
}

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

Sub.prototype = new Super();

var sub = new Sub();

然后,在我們ocde的其他部分,我們可以使用以下任一方法來檢查關系:

sub instanceof Super;   

要么

Super.prototype.isPrototypeOf( sub )

無論哪種方式,我們都需要同時擁有對象(sub)和父構造函數(Super)。 那么,你有沒有理由使用其中一個? 還有其他一些區別更明確的情況嗎?

我已經仔細閱讀了2464426 ,但沒有找到足夠具體的答案。

想象一下,您不在代碼中使用構造函數 ,而是使用Object.create生成具有特定原型的對象。 您的程序可能被架構為根本不使用構造函數:

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

在這里,您沒有與instanceof一起使用的構造函數。 您只能使用subProto.isPrototypeOf(sub)

使用構造函數時,它幾乎沒有什么區別。 也許, instanceof有點干凈。 但是當你不......時:

var human = {mortal: true}
var socrates = Object.create(human);
human.isPrototypeOf(socrates); //=> true
socrates instanceof human; //=> ERROR!

所以isPrototypeOf更通用。

根據MDN Ref

isPrototypeOf()instanceof運算符不同。 在表達式object instanceof AFunction ,對象原型鏈將針對AFunction.prototype進行檢查,而不是針對AFunction本身。

var neuesArray = Object.create(Array);

Array.isPrototypeOf(neuesArray);            // true
neuesArray instanceof Array                 // false
neuesArray instanceof Object                // true
Array.isArray(neuesArray);                  // false
Array.prototype.isPrototypeOf(neuesArray);  // false
Object.prototype.isPrototypeOf(neuesArray); // true

你了解我的朋友:) - 很簡單

只是補充@ apsillers的答案

object instanceof constructor

var superProto = {}

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

console.log(superProto.isPrototypeOf(sub)); // true
console.log(sub instanceof superProto); // TypeError: Right-hand side of 'instanceof' is not callable

// helper utility to see if `o1` is
// related to (delegates to) `o2`
function isRelatedTo(o1, o2) {
  function F(){}
  F.prototype = o2;
  // ensure the right-hand side of 'instanceof' is callable
  return o1 instanceof F; 
}
isRelatedTo( b, a ); 

TypeError:'instanceof'的右側不可調用

instanceof需要右側值可調用,這意味着它必須是一個函數(MDN將其稱為構造函數)

instanceof測試對象原型鏈中constructor.prototype的存在。

isPrototypeOf()沒有這樣的限制。 instanceof檢查superProto.prototypeisPrototypeOf()直接檢查superProto

暫無
暫無

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

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