I am struggling with the keyword 'instance'. In Java, I only know how to create the "new" keyword. Now, I'm learning about JavaScript, some author heavily used the word 'instance':
function Foo(){}
var foo = new Foo();
//foo is now an instance of Foo
console.log(foo instanceof Foo ) //=> true
What is the purpose of making foo instanceof Foo
?
instanceof is a binary operator, The instanceof allows to check if the object is created by given constructor:
The instanceof operator returns true if object is an instance of class. It returns true if true if class is present in the object's prototype chain. It returns false if object is not an instance of class, or if object is null.
function Rabbit() { }
var rabbit = new Rabbit
alert(rabbit instanceof Rabbit) // true
In the example above, the match is found at the first step, because: rabbit.proto == Rabbit.prototype.
Few helpful links
What is the instanceof operator in JavaScript?
http://www.w3schools.com/js/js_objects.asp
http://javascript.info/tutorial/instanceof#the-instanceof-operator
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句