gpt4 book ai didi

javascript - JS 原型(prototype)不工作

转载 作者:行者123 更新时间:2023-11-29 19:53:21 24 4
gpt4 key购买 nike

有人可以看看这个并帮助我理解为什么 prototype.placing 不是控制台日志记录吗?感谢您的帮助:

(function() {
function Rider(name) {
this.name = name;
this.show = function(showName) {
console.log(this.name + " rode in the " + showName);
};
}

var riderOne = new Rider("Billy Bobb");
riderOne.show("Summer Show");

Rider.prototype.placing = function(place) {
console.log(this.rider + " ended up in " + place + " at " +
this.showName);
}
})();

最佳答案

看看这里,它正在工作:http://jsfiddle.net/D3BKz/1/

代码:

(function() {
function Rider(name) {
this.name = name;
this.showName = "";
this.show = function(showName) {
this.showName = showName;
console.log(this.name + " rode in the " + showName);
};
}
Rider.prototype.placing = function(place) {
console.log(this.name + " ended up in " + place + " at " +
this.showName);
}
var riderOne = new Rider("Billy Bobb");
riderOne.show("Summer Show");
riderOne.placing("1st");

})();

我改变了这个:

Rider.prototype.placing = function(place) {
console.log(this.rider+ " ended up in " + place + " at " +
this.showName);
}

为此:

Rider.prototype.placing = function(place) {
console.log(this.name + " ended up in " + place + " at " +
this.showName);
}

然后我用

riderOne.placing("1st");

这是控制台输出:

Billy Bobb rode in the Summer Show
Billy Bobb ended up in 1st at Summer Show

编辑:

正如有人指出的那样,showName 从未在您的 Rider 类中定义。我更新了代码,将 showName 属性添加到类中。

关于javascript - JS 原型(prototype)不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16874728/

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