1

プロパティとメソッドを使用してコンストラクターを作成する方法を理解することで、私は自分の道を進んでいます。以下のものは私が書いてテストしましたが、うまくいきません。誰かが時間をかけて、これがうまくいかない理由を理解するのを手伝ってくれませんか. 私は Google で検索したり、本を読んだりしていますが、自分で作成した概念を理解するには、実践的なサポートが必要であることを理解してください。ありがとうございました。

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

プレーヤー関数では、変数 who、how、type、shape、およびこれを使用してグリップする必要があります。つまり、

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

さらに、タイプ ball のすべてのオブジェクトに共通の関数をプロトタイプに入れ、関数が 1 回だけ作成されるようにする必要があります。

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(ball)ではなくconsole.log(baseball)を実行するだけで済みます。また、次のように、プレーヤー関数の戻り行の最後と最初に引用符が必要です。

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