【问题标题】:JavaScript base type is `instanceof` derived type's constructorJavaScript 基类型是 `instanceof` 派生类型的构造函数
【发布时间】:2017-06-24 13:10:04
【问题描述】:

我有一个cat,它继承自animal

我希望 cat 是其构造函数和 animal 构造函数的实例。

animal 也是 cat 构造函数的一个实例。

var animal = {};

var cat = Object.create(animal);

console.log('cat instanceof animal.constructor: ' + (cat instanceof animal.constructor));
console.log('   cat instanceof cat.constructor: ' + (cat instanceof cat.constructor));
console.log('animal instanceof cat.constructor: ' + (animal instanceof cat.constructor));

为什么animalcat 的一个实例?

【问题讨论】:

  • 试试console.log(cat.constructor, cat.constructor === animal.constructor);
  • @4castle 谢谢,但是为什么他们是平等的?我不明白我的派生类型和我的基类型如何具有相同的构造函数。
  • cat 实际上并没有定义其constructor 属性,因此当您尝试访问cat.constructor 时,它使用原型对象的constructor 值。
  • @4castle 好的,那么Object.create 方法将设置新对象的原型,但将使用Object 对象的构造函数构造它?这是否意味着它是分两部分创建的,创建对象然后设置其属性?
  • 我们不知道它实际上使用的是什么构造函数。我们只知道它从您用来调用Object.create 的对象继承constructor 属性。尝试做console.log(Object.create(null).constructor);

标签: javascript oop prototype prototypal-inheritance


【解决方案1】:

下面的代码可能会让你理解这个概念。

instanceoftypeofconstructor 之间存在区别

  • instanceof:检查整个链条
  • Object.prototype.constructor:返回对创建实例对象的 Object 构造函数的引用
  • typeof:返回任何考虑的数据类型

现在在你的情况下:检查 cmets

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

【讨论】:

  • 这一行是否正确:“constructor: 只返回构造该对象的任何内容”。似乎情况并非如此,因为 cat 构造函数是 Object 构造函数。
  • 我应该改写它@BanksySan
猜你喜欢
  • 2020-02-28
  • 2016-07-19
  • 1970-01-01
  • 2023-03-10
  • 2018-07-16
  • 1970-01-01
  • 2018-07-21
  • 2016-12-20
  • 1970-01-01
相关资源
最近更新 更多