2012-10-22 16 views
1

我工作的一個Javascript和我被困了一些驗證:如何檢查的instanceof對象的實例,在Javascript

我想檢查作爲參數變量是一個實例一個對象的實例。爲了更清楚,這裏有一個例子:

var Example = function() { 
    console.log ('Meta constructor'); 
    return function() { 
     console.log ('Instance of the instance !'); 
    }; 
}; 

var inst = new Example(); 
assertTrue(inst instanceof Example.constructor); // ok 

var subInst = new inst(); 
assertTrue(subInst instanceof Example.constructor); // FAIL 
assertTrue(subinst instanceof inst.constructor); // FAIL 

我如何檢查subInstExample.{new}一個實例?或inst.constructor

謝謝! :)

+1

檢查了這一點 http://stackoverflow.com/questions/2449254/what-is-the-instanceof-operator-in-javascript – TheITGuy

回答

1
subInst.__proto__ == inst.prototype 
+0

顯然,使用inst.constructor並不好,在那種情況下如何檢查inst的來源? –

1

首先,你不檢查對.constructor,你檢查構造函數,即Example。無論何時測試.constructor屬性,這將是實例上發現的屬性(如果您將其設置爲構造函數的原型)。

所以

(new Example) instanceof Example; // true 

其次,如果你Example函數返回一個函數,然後Example實際上不是一個構造函數,因此你不能做任何它的原型繼承檢查。構造函數將始終返回一個對象,該對象將是構造函數的一個實例。

您擁有的是一個工廠函數,它可以創建可能將用作構造函數的函數。函數只會通過instanceof檢查FunctionObject

var Ctor = example(); // PascalCase constructor, camelCase factory 
var inst = new Ctor(); 
inst instanceof Ctor; // true 

但做看看張貼@franky的鏈接,它應該給你一些見解,你需要做什麼。

+0

'(新例)的instanceof例;'我錯誤與Chrome:/ –

+0

@CyrilN。這是因爲/你的/'Example'函數不是一個構造函數,而是一個工廠函數。 –

+0

好的,有趣! :)我需要有一個像我在我的問題中使用的行爲。這是做這件事的最好方式還是有更好的辦法? –