javascript Object.create()

时间:2016-05-06 10:48:11

标签: javascript object prototype

function Shape() {}

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

function Rectangle() {
  Shape.call(this); 
}

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

console.log('Is rect an instance of Rectangle?', rect instanceof Rectangle);// true
console.log('Is rect an instance of Shape?', rect instanceof Shape);// true
rect.move(1, 1); // Outputs, 'Shape moved.'

我从MDN遇到过这个例子。 我是否知道将Rectangle.prototype = Object.create(Shape.prototype);替换为Rectangle.prototype = Shape.prototype;是否会发生重大变化? 两种情况下的结果都相同。 我被告知prototype属性本身就是一个对象,为什么我们首先使用object.create()来创建另一个对象然后将它分配给矩形的属性?为什么没有直接将形状原型分配给矩形?

3 个答案:

答案 0 :(得分:1)

让我们展开你的例子,看看差异。

function Shape() {}

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

function Rectangle() {
  Shape.call(this); 
}

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

Rectangle.prototype.move = function(x, y) {
  console.info('Rectangle moved.');
};

var shape = new Shape();
var rect = new Rectangle();
console.log('Is rect an instance of Rectangle?', rect instanceof Rectangle);// true
console.log('Is rect an instance of Shape?', rect instanceof Shape);// true
shape.move(1, 1); // 'Shape moved.'
rect.move(1, 1); // 'Rectangle moved.'

现在让我们看看当您不使用Object.create()时会发生什么:

function Shape() {}

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

function Rectangle() {
  Shape.call(this); 
}

Rectangle.prototype = Shape.prototype;

Rectangle.prototype.move = function(x, y) {
  console.info('Rectangle moved.');
};

var shape = new Shape();
var rect = new Rectangle();
console.log('Is rect an instance of Rectangle?', rect instanceof Rectangle);// true
console.log('Is rect an instance of Shape?', rect instanceof Shape);// true
shape.move(1, 1); // 'Rectangle moved.'
rect.move(1, 1); // 'Rectangle moved.'

如果不使用Object.create()基于Shape.prototype对象创建新原型,则只需指定对现有原型的引用,稍后在覆盖部分{{1在原型方法中,你实际上也覆盖了Rectangle的原型方法,因为它是同一个对象。

答案 1 :(得分:0)

如果您使用

Rectangle.prototype = Shape.prototype;

Rectangle Shape 原型将是同一个对象,您添加到 Rectangle 的每个方法/属性都将出现在中塑造

答案 2 :(得分:0)

此方法Rectangle.prototype = Object.create(Shape.prototype);将确保Shape.prototype根据Rectangle基本功能继承Shape.prototype。这可以防止Shape.prototype修改Rectangle.prototype 请考虑以下事项:

...
Rectangle.prototype = Shape.prototype; // Shape.prototype is assigned as reference
var rect = new Rectangle();

Rectangle.prototype.add = "add method";
console.log(JSON.stringify(Shape.prototype,0,4));
...
// the output will be like(Shape.prototype was changed):
{
    "add": "add method"
} 

如您所见,将Shape.prototype直接指定给Rectangle.prototype作为参考,允许Rectangle.prototype修改Shape.prototype
Object.create(Shape.prototype)将被分配作为新的"独立的"对象(所有Rectangle.prototype扩展名不会影响Shape.prototype