1

我正在通过了解如何创建具有属性和方法的构造函数来工作。我已经编写并测试了下面的一个,但它不起作用。有人可以花时间帮助我了解是什么导致这不起作用。了解我已经搜索过谷歌,我正在阅读书籍等,但需要一些帮助来理解这个概念并创建我自己的。谢谢你。

function ball( type, grip, shape ) {
  this.type = type;
  this.grip = grip;
  this.shape = shape;
  this.caught = function( who,how ) {
    this.who = who;
    this.how = how;
  };
  this.player = function() {
    return (who + "caught the ball" + how + "that was a" + type + "shaped like 
            a " + shape + "thrown with a" + grip);
    };
};

var baseball = new ball("Mickey Mantle","sliding","baseball","circle","fastball");

console.log(ball);

编辑: 从下面的答案中-感谢您的分享-我已经创建了我的 jsfiddle,但无法理解为什么被捕获的属性不起作用。我应该如何设置此方法的属性?

http://jsfiddle.net/uYTW6/

4

3 回答 3

1

http://jsfiddle.net/rvMNp/1/

您应该这样做console.log(baseball)以获取当前对象。

同样在我的小提琴中,您会注意到您的播放器功能无法按预期工作。这是因为你的很多变量是未定义的。


new ball("Mickey Mantle","sliding","baseball","circle","fastball");

这是用 5 个变量调用球函数,但你的球函数只接受 3

function ball( type, grip, shape )


您还需要使用this.*函数中定义的任何变量,如下所示:

return (this.who + "caught the ball" + this.how + "that was a" + this.type + "shaped like a " + this.shape + "thrown with a" + this.grip);
于 2012-08-31T11:02:24.777 回答
1

在您的播放器函数中,您需要使用 this 引用变量 who、how、type、shape 和 grip,即

return (this.who + "caught the ball" + this.how + "that was a" + this.type + "shaped like 
        a " + this.shape + "thrown with a" + this.grip);
};

此外,所有 ball 类型的对象共有的函数应该放入原型中,这样该函数只会被创建一次:

ball.prototype.player = function() {
    return (this.who + "caught the ball" + this.how + "that was a" + this.type + "shaped like a " + this.shape + "thrown with a" + this.grip);
    };
}

以大写字母开头的构造函数名称也是常见的约定,例如在您的情况下为 B (因此您的构造函数的名称是 Ball,而不是 ball)。

更新的答案

您忘记调用caught棒球对象上的函数,如下所示:

var baseball = new Ball("Mickey Mantle","sliding","baseball","circle","fastball");
baseball.caught('me', 'by hand');
于 2012-08-31T11:02:25.330 回答
0

您只需要执行 console.log(baseball) 而不是 console.log(ball) 即可查看您创建的对象。此外,您需要在播放器函数的返回行的末尾和开头加上引号,如下所示:

return (who + "caught the ball" + how + "that was a" + type + "shaped like "+
        "a " + shape + "thrown with a" + grip);
};
于 2012-08-31T11:04:27.517 回答