javascript - object.Create 返回的对象类型

标签 javascript

我正在尝试掌握 Javascript 的某些概念。这是一个小情况

// Shape - superclass
function Shape() {
  this.x = 0;
  this.y = 0;
}

// superclass method
Shape.prototype.move = function(x, y) {
  this.x += x;
  this.y += y;
  console.info('Shape moved.');
};

// Rectangle - subclass
function Rectangle() {
  Shape.call(this); // call super constructor.
}

// subclass extends superclass
Rectangle.prototype = Object.create(Shape.prototype)

现在,如果我输入

Rectangle.prototype instanceof Shape
true

现在,这是否意味着返回对象的类型 Object.create (在我的第一个代码片段的最后一行)是 Shape ?看来是的。虽然我没有在任何地方请求它,但我只是指定了该对象的原型(prototype),它应该与 Shape.prototype 相同。 .

我只是在 Object.create 中找不到此记录文档。有人可以解释一下是否是这种情况以及(也许也)为什么是这样吗?

额外:另外,似乎是通过使用线

Rectangle.prototype = Object.create(Shape.prototype)

我继承的是方法,而不是 Shape 中声明的实例变量构造函数?因为原型(prototype)不知道 Shape 中指定的属性。构造函数?例如xy .

最佳答案

Does it mean the type of the object returned by Object.create (in my last line of first code snippet), is Shape?

没有。没有 Shape 类型。 ECMAScript 只有以下类型:Undefined、Null、Boolean、Number、String、Symbol、Object。

Object.create返回的值属于Object类型。

I just specified the prototype of that object which should be same as Shape.prototype.

是的,这正是您所得到的。 Object.create 返回一个新的不可调用的普通对象,其 [[Prototype]] 为参数。

instanceof 运算符默认只检查原型(prototype)链,即属性继承。它不能确保所谓的实例确实是由构造函数构造的。

关于javascript - object.Create 返回的对象类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40349376/

相关文章:

javascript - 在 Angular 项目中到达 "/phone"的 URL 是什么?

javascript - 在对象中显示字符串

javascript - 无法在 Parse.com 上保存类(class)

javascript - 如何在 jQuery 日期选择器中指定多个选项

javascript - jQuery不同元素上的不同事件触发相同的功能

javascript - Array.fill 与赋值时的文字 2D 定义不同

javascript - 如何撤消 chrome devtools 上的 pretty-print

javascript - 在 web 应用程序中实现 facebook 共享时 Error get The parameter app_id is required

javascript - 动态添加时,第二个 Google map 无法正确呈现

javascript - 简单的ajax请求加载外部json文件