can对象是多种类型的实例?

时间:2015-03-25 10:41:40

标签: javascript instanceof

function Hero(name) {
    this.name = name;
}
var h = new Hero('Leonardo');
var a = h instanceof Hero;
var b = h instanceof Object;`

在这里,我可以理解一个将是真实的'。但是当我在Firefox控制台中检查时,b也是真的' true'。为什么会这样?

3 个答案:

答案 0 :(得分:1)

对象是其原型链上所有内容的实例:



function Animal() {
}

function Cat() {
}

function Dog() {
}

Cat.prototype = Object.create(Animal.prototype);
Dog.prototype = Object.create(Animal.prototype);

var felix = new Cat();
snippet.log("Felix");
snippet.log("Object - " + (felix instanceof Object));
snippet.log("Animal - " + (felix instanceof Animal));
snippet.log("Cat    - " + (felix instanceof Cat));
snippet.log("Dog    - " + (felix instanceof Dog));

snippet.log("-----------");

var spike = new Dog();
snippet.log("Spike");
snippet.log("Object - " + (spike instanceof Object));
snippet.log("Animal - " + (spike instanceof Animal));
snippet.log("Cat    - " + (spike instanceof Cat));
snippet.log("Dog    - " + (spike instanceof Dog));

<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

归因于Prototype Inheritance,每个ArrayFunction等都会遇到对象,作为每件事物的父母/终极父母

a = [];
b = function(){}
a instanceof Object // true
b instanceof Object // true

答案 2 :(得分:0)

在Javascript中,所有本机函数都从基类Object继承。所以所有对象都是Object的实例。

Check Array,String,都是Object的实例。

javascript中必须知道的事实。