2016-06-11 3 views
-2

codewars.comからのJavascriptチャレンジに固執しています。それはコンストラクタ(?)関数のように見えますが、私は知っていると思っていました。 私はMDNや他の場所で例を探しました。 私は自分自身を描くことができるかどうかを知るために、まっすぐな答えよりもむしろ間違った点を知っています。 挑戦:コードワードのコンストラクタ

function new Person(name){ 
    this.name = name; 
    return name; 
} 
Person.prototype.greet = function(otherName){ 
    return "Hi " + otherName + ", my name is " + name; 
}; 

私は多分両方の名前のコンストラクタに追加すると、それを行うが、再び「予期しないトークン新しい」エラーを取得するだろうと思ったいくつかの研究を行うことによって。私の試み:私の無知と

function new Person(name, otherName){ 
 
    this.name = name; 
 
    this.otherName = otherName; 
 
    return name + " " + otherName; 
 
} 
 

 
Person.prototype.greet = function(otherName){ 
 
    return "Hi " + otherName + ", my name is " + name; 
 
}; 
 
var fullName = new Person("Fred", "Jones"); 
 
greet.fullName();

忍耐は大歓迎です。 ありがとう、 pychap

+0

に配置された説明をお読みください[尋ねます]。ここに適切な問題文はありません。具体的な質問はありません。 – charlietfl

+0

* javascript factory pattern *のグーグルを試してみて、それを試してから、より一貫性のある例に戻ってください。私たちはあなたを助けてうれしい! – pietro909

答えて

0

あなたが試したコードはかなり間違っていますが、(あなたがそれを学ぶことを試みているので)コードを与えるのではなく、私はあなたにいくつかの指摘をします。

function宣言の後にキーワードnewを使用することはできません。メソッドの新しいインスタンスを作成するために使用されますnew Person()

greetメソッド内では、nameは定義されていません。名前を取得するには、適切なスコープを使用する必要があります。

greet.fullName()も定義されていないため、fullName変数のメソッドにアクセスしてください。編集した

+2

また、一般にcontructor関数は何も返さないでください。 – Barmar

-1

function Person(firstName, lastName){ //declaration of function named person taking 2 arguments 
 
    this.firstName = firstName; //creating variable holding firstName 
 
    this.lastName = lastName; //same as above but for lastName 
 
//removed return as constructor functions shouldnt return anything, you call this function with 'new' which already creats content of your object 
 
} 
 

 
Person.prototype.greet = function(){ //this is another declaration but for greet function. You can think about it like a function you can call but only for variables holding Person object 
 
    return "Hi " + this.firstName + " " + this.lastName; //use 'this' to tell your program to work on object that calls this function (greet()) 
 
}; 
 

 
var fullName = new Person("Fred", "Jones"); //this is point of your program - in variable fullName it creates an object using your function Person. Since now all methods that has Person you can call on fullName variable. 
 
console.log(fullName.greet()); // here I use console.log to print resutl of fullName.greet() call. I defined fullName and I have put object into it created with Person function. Now I place fullName first, then calling one of methods it owns - greet(). Result is sentence defined in greet declaration.

:コメント

+1

Downvoteなぜあなたがこれを修正するのかについての説明なしに、修正するためのコードを提供していたからです。 –

+0

ああ、それでは、どうなるか説明します。編集を開始します。 –

+1

なぜ 'return'文を' Person() '関数から削除しましたか?私は答えを知っていますが、あなたは答えでそれを説明する必要があります。 – Barmar

関連する問題