JS构造函数

时间:2012-08-31 10:56:21

标签: javascript

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

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/

3 个答案:

答案 0 :(得分:1)

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

你应该console.log(baseball)来获取当前对象。

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


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

这是用5个变量调用ball函数,但你的ball函数只接受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);

答案 1 :(得分:1)

在你的玩家功能中,你需要使用它来引用变量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');

答案 2 :(得分:0)

您只需要执行console.log(棒球)而不是console.log(ball)来查看您创建的对象。此外,您需要在播放器功能的返回行的结尾和开头处使用引号,如下所示:

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