【发布时间】: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