0

以下のコンストラクター関数に名前と色を送ってみます。メソッドthis.whatAreYou()は、呼び出されたときにこれらの文字列を取得する必要があります。

これを画面に表示したい。

私は次のコードを持っています:

function Gadget(name, color) {
    this.name = name;
    this.color = color;
    this.whatAreYou = function() {
        return 'I am a ' + this.name+ ' ' + this.color;
    };
}

string = Gadget(grass, green);
alert(string);​

ただし、アラートは機能していません。どうすれば希望の動作を実現できますか?

4

4 に答える 4

2

ガジェットは文字列ではありません。文字列を返す関数を保持するだけです。

Gadgetクラスのインスタンスを作成しようとしているように見えるので、new演算子を使用する必要があります。

grassおよびgreenが事前定義された変数ではなく文字列である場合は、それらを引用符で囲む必要があります。

試す

var g = new Gadget('grass', 'green');
alert(g.whatAreYou());​
于 2012-09-18T16:37:41.487 に答える
1

ガジェットに渡されるパラメータが引用符で囲まれていないなど、いくつか間違っています。そして、whatAreYou()を呼び出すことはありません。

    <script type="text/javascript">

    function Gadget(name, color) {
        this.name = name;
        this.color = color;
        this.whatAreYou = function () {
            return 'I am a ' + this.name + ' ' + this.color;
        };
        return whatAreYou();
    }

    alert(Gadget('grass', 'green'));


</script>
于 2012-09-18T16:45:35.573 に答える
1

演算子をGadget使用するインスタンスを作成する必要があります。new

var gadget = new Gadget('grass', 'green');
var string = gadget.whatAreYou();
alert(string);
于 2012-09-18T16:38:23.553 に答える
1
function Gadget(name, color) {
    this.name = name;
    this.color = color;
    this.whatAreYou = function() {
        return 'I am a ' + this.name+ ' ' + this.color;
    };
return this.whatAreYou;
}

string = Gadget(grass, green);
alert(string);​
于 2012-09-18T16:42:57.267 に答える