【问题标题】:Why is the function prototype not working in this fiddle?为什么函数原型在这个小提琴中不起作用?
【发布时间】:2015-12-27 17:26:34
【问题描述】:

我试图使用 javascript 函数原型打印 vehicle 对象 in my fiddle 的值。

function carDetails() {
  var car = new vehicle("Red", "Car");
  car.getPrice(100);

  // Define a function which will work as a method
  vehicle.prototype.price = function getPrice(amount) {
    car.price = amount;
  };

  document.getElementById("color").innerHTML = car.color;
  document.getElementById("type").innerHTML = car.type;
  document.getElementById("price").innerHTML = car.price;

}

function vehicle(color, type) {
  this.color = color;
  this.type = type;
  //this.prototype.price = getPrice;
}

vehicle.prototype.getPrice = getPrice;

carDetails();
<h1>
Javascript function prototypes
</h1>
<p id='color'></p>

<p id='type'></p>

<p id='price'></p>

为什么vehicle 对象没有被打印出来?

【问题讨论】:

  • 你看控制台了吗?可以看到“Uncaught TypeError: car.getPrice is not a function”。
  • 为什么你的 setter 被命名为 getter?
  • @Ramsharan 是的,但功能在那里。对吗?
  • 您的代码中根本没有使用原型工具。
  • 代码中的任何地方都没有原型,而您的 setter 就是您设置价格的地方。 this.price = amount 您说您正在学习该教程,但您从未使用过第 1 步中的 prototype

标签: javascript html prototype prototype-programming function-prototypes


【解决方案1】:
function vehicle(color, type) {
  this.color = color;
  this.type = type;
  this.price = getPrice;
}

 car.getPrice(100);

该属性是price in,您使用的是getPrice()

另外,在原型上设置 set functions 以避免函数对象在每次构造函数调用时被创建。

【讨论】:

  • 我更新了my fiddle,但输出没有变化。
  • @student 小提琴中的代码有很多问题。我敦促您阅读 MDN 上有关函数范围和原型链的更多信息,这意味着虽然这里有一个工作小提琴:jsfiddle.net/aht2fpts/1,但我已经做了一些更改。
  • 小提琴+3。我会尝试同样使用prototypes。
【解决方案2】:
function carDetails() {
  var car = new vehicle("Red", "Car");
  car.getPrice(100);

  document.getElementById("color").value = car.color;
  document.getElementById("type").value = car.type;
  document.getElementById("price").value = car.price;

}

// Define a function which will work as a method
function getPrice(amount) {
  this.price = amount;
}


function vehicle(color, type) {
  this.color = color;
  this.type = type;
  this.getPrice = getPrice;
}

carDetails();

It will work

【讨论】:

  • 而且你没有在这段代码中实现任何原型
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-05-26
  • 2016-01-13
  • 2022-12-03
  • 2021-06-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多