2012-10-22 21 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

好的,有趣! :)我需要有一个像我在我的问题中使用的行为。这是做这件事的最好方式还是有更好的办法? –