Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
JavaScript基类型是`instanceof`派生类型';s构造函数_Javascript_Oop_Prototype_Prototypal Inheritance - Fatal编程技术网

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