JS原型不起作用

时间:2013-06-01 16:23:44

标签: javascript

有人可以看看这个并帮助我理解为什么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);
    }
})();

1 个答案:

答案 0 :(得分:3)

看看这里,它正在运作: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属性添加到类中。