JavaScript基类型是`instanceof`派生类型';s构造函数
我有一只猫,它继承自动物 我希望JavaScript基类型是`instanceof`派生类型';s构造函数,javascript,oop,prototype,prototypal-inheritance,Javascript,Oop,Prototype,Prototypal Inheritance,我有一只猫,它继承自动物 我希望cat是其构造函数和animal构造函数的实例 animal也是cat构造函数的一个实例 var-animal={}; var cat=Object.create(动物); log('cat instanceof animal.constructor:'+(cat instanceof animal.constructor)); log('cat instanceof cat.constructor:'+(cat instanceof cat.construct
cat
是其构造函数和animal
构造函数的实例
animal
也是cat
构造函数的一个实例
var-animal={};
var cat=Object.create(动物);
log('cat instanceof animal.constructor:'+(cat instanceof animal.constructor));
log('cat instanceof cat.constructor:'+(cat instanceof cat.constructor));
log('cat.constructor的动物实例:'+(cat.constructor的动物实例))代码>下面的代码可能会让您理解这个概念
instanceof
、typeof
和constructor
instanceof
:检查整个链
Object.prototype.constructor
:返回对创建实例对象的对象构造函数的引用
typeof
:返回所考虑的数据类型
现在在您的案例中:检查注释
var animal = {}; //animal is an object
//animal.constructor is a parent Object constructor function
var cat = Object.create(animal);
//cat is an object created using animal object
//cat.constructor will also return parent Object constructor because.
//To remember this just remember that right side of instanceof always needs to be callable (that is, it needs to be a function)
console.log('cat instanceof animal.constructor: ' + (cat instanceof animal.constructor));
//this will return true as animal.constructor is nothing but parent Object constructor function and every object is instanceof that parent Object()
console.log(' cat instanceof cat.constructor: ' + (cat instanceof cat.constructor));
//this will also return true for the same reason as mentioned above
console.log('animal instanceof cat.constructor: ' + (animal instanceof cat.constructor));
//this also has the same reason
尝试console.log(cat.constructor,cat.constructor==animal.constructor)代码>@4castle谢谢,但为什么他们是平等的?我不明白我的派生类型和基类型如何具有相同的构造函数。cat
实际上没有定义它的constructor
属性,因此当您尝试访问cat.constructor
时,它使用原型对象的constructor
值。@4castle OK,因此,Object.create
方法将设置新对象的原型,但将使用Object
对象的构造函数来构造它?这是否意味着它分两部分创建,创建对象,然后设置其属性?我们不知道它实际使用的构造函数是什么。我们只知道它从用于调用object.create
的对象继承了构造函数
属性。尝试执行console.log(Object.create(null.constructor))代码>这行是否正确:“构造函数
:只返回该对象构造的内容”。似乎情况并非如此,因为cat
构造函数是对象
构造函数。我最好将其改写为@BanksySan