gpt4 book ai didi

javascript - 如何正确设置原型(prototype)?

转载 作者:太空宇宙 更新时间:2023-11-04 02:15:12 24 4
gpt4 key购买 nike

我正在练习一本名为 Object-Oriented JavaScript 的书中的练习。 .

第 5 章的练习包含以下 4 个问题:

  1. Create an object called shape that has the type property and a getType() method.
  2. Define a Triangle() constructor function whose prototype is shape. Objects created with Triangle() should have three own properties—a, b, and c, representing the lengths of the sides of a triangle.
  3. Add a new method to the prototype called getPerimeter().
  4. Test your implementation with the following code:

.

  var t = new Triangle(1, 2, 3);
t.constructor === Triangle; // true
shape.isPrototypeOf(t); // true
t.getPerimeter(); // 6
t.getType(); // "triangle"

这是我对上述问题的解决方案:

var shape = {
type: 'triangle',
getType: function() {
return this.type;
}
};

function Triangle(a, b, c) {
this.a = a;
this.b = b;
this.c = c;
}

Triangle.prototype = shape; // Maybe something goes wrong here

Triangle.prototype.getPerimeter = function() {
return this.a + this.b + this.c;
}

// ======================================================
var t = new Triangle(1, 2, 3);
console.log(t.constructor === Triangle); // false
console.log(shape.isPrototypeOf(t)); // true
console.log(t.getPerimeter()); // 6
console.log(t.getType()); // triangle

为什么console.log(t.constructor === Triangle);输出false作为结果?

我尝试删除 console.log(t.constructor === Triangle);,这使得 t.constructor === Triangle 等于 true,但会导致 TypeError: t.getType is not a function 错误。

怎样才能让我的执行结果和本书提供的答案一样?

最佳答案

添加

Triangle.prototype.constructor = Triangle;

之后

Triangle.prototype = shape;

解决了我的问题。

在第 6 章第 173 页,书上说

Overwriting the prototype has side effects on the constructor property. Therefore, it's a good idea to reset the constructor after inheriting

关于javascript - 如何正确设置原型(prototype)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36080617/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com