2017-07-08 49 views
2

如果我们从函数构造函数创建一个名为'a'的对象,那么为什么'a'不是函数的实例?

function person(first, last, age, eye) { 
 
    this.firstName = first; 
 
    this.lastName = last; 
 
    this.age = age; 
 
    this.eyeColor = eye; 
 
} 
 
var myFather = new person("John", "Doe", 50, "blue"); 
 
console.log(myFather instanceof person); //true 
 
console.log(myFather instanceof Object); //true 
 
console.log(myFather instanceof Function); //false

你好,在这种情况下,我们创建从函数构造一个对象: '人'。

JavaScript中的每个函数都是Function构造函数的一个实例。 为什么myFather不是Function的一个实例?

+2

因为通过'myFather'引用的对象是由人'()'构造* *创建一个普通的对象。当你用'new'调用函数时,会创建一个新对象,并在构造函数上下文中绑定到'this'。 – Pointy

+0

原型链是myFather - > person.prototype - > object.prototype。 instanceof检查 –

回答

3

myFatherperson一个对象实例,这就是为什么它返回的myFather instanceof Object真实的,但假的myFather instanceof Function,因为它不是一个函数,但一个对象,你不能myFather再打电话来实例化另一个对象。其实person是Function的一个实例。当您致电new person时,会返回一个普通对象并将其存储在myFather中。

function person(first, last, age, eye) { 
 
    this.firstName = first; 
 
    this.lastName = last; 
 
    this.age = age; 
 
    this.eyeColor = eye; 
 
} 
 
var myFather = new person("John", "Doe", 50, "blue"); 
 
console.log(myFather instanceof person); //true 
 
console.log(myFather instanceof Object); //true 
 
console.log(myFather instanceof Function); //false 
 
console.log(person instanceof Function); //true

+0

啊好吧,我现在明白了。非常感谢 – JohannaNoobie

相关问题