javascript - 了解 Object.create

标签 javascript

阅读 Object.create 后文档。我对其做了一些测试。 这是我的代码。请查看。

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

Shape.prototype.move = function(x, y) {
    this.x += x;
    this.y += y;
    console.info("Shape moved.");
};

Rectangle=Object.create(Shape);

Rectangle.move(); //?? why move function is not found ?

正如文档所说,Object.create(proto[,propertiesObject]); proto 应该是新创建对象的原型(prototype)。 因此,Rectangle.prototype 应该与 Shape 相同。但实际上并非如此。显然我不明白文件的这一部分。我仍然发现 Rectangle.__proto__==Shape 是正确的。 OK,即使 Rectangle.__proto__==Shape 为 true ,为什么 Rectangle 找不到 move 函数呢? move 函数不在原型(prototype)链中吗?我以为 move 函数在 Rectangle.__proto__.prototype 中,它应该在链中找到。为什么不能?谢谢。

最佳答案

原型(prototype)必须是一个实际的对象。在这种情况下,您应该传递 Shape 的原型(prototype),而不是 Shape 函数。

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

Shape.prototype.move = function(x, y) {
    this.x += x;
    this.y += y;
    console.info("Shape moved.");
};

Rectangle=Object.create(Shape.prototype, {a:1});

Rectangle.move(); // it will call now
Rectangle.a; // 1
Rectangle.x; // NaN ???
Rectangle.y; // NaN ???

请注意Object.create()与使用 new 不同关键字 - 这可能就是您正在寻找的内容。

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

Shape.prototype.move = function(x, y) {
    this.x += x;
    this.y += y;
    console.info("Shape moved.");
};

Rectangle=new Shape;

Rectangle.move(1,2); // works properly now
Rectangle.a; // undefined, we never made one
Rectangle.x; // 1
Rectangle.y; // 2

由于 Javascript 实际上会查找构造函数及其 .prototype要递归地查找原型(prototype),它不会查找 Shape 的原型(prototype),因为它不是直接设置的,new 也不是直接设置的。用于创建 Rectangle 的构造函数:

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

Shape.prototype.move = function(x, y) {
    this.x += x;
    this.y += y;
    console.info("Shape moved.");
};

Rectangle = Object.create(Shape);
Rectangle.constructor; // Function()
Rectangle.constructor.prototype; // That's Function.prototype
/* as you can see Shape.prototype is never touched by the prototype chain */

Rectangle.__proto__; // Shape(), not the prototype (doesn't have any direct properties on it)

Rectangle.move(1,2); // TypeError: Rectangle.move is not a function
Rectangle.a; // does not exist
Rectangle.x; // function never called on Rectangle, so also doesn't exist
Rectangle.y; // function never called on Rectangle, so also doesn't exist

关于javascript - 了解 Object.create,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16196064/

相关文章:

javascript - Bootstrap TextArea 在 IE11 中不可调整大小

javascript - 拆分曾经是列表的字符串

javascript - 使用JavaScript进行代码依赖来选择RESTful

javascript - Fabricjs:显示横幅预览

javascript - 悬停不适用于图片库

javascript - 控制台错误返回 false

javascript - 计算 JSON 中的键/值

javascript - 带有子类的构造函数中的 Object.freeze

javascript - 如何迭代特定索引并检查 javascript/angular 中的值

javascript - 已弃用的 Webpack 的 i18n 插件和加载器的替代品