2016-05-08 9 views
0

ここに新しいオブジェクトを作成しようとしています。 は、ここに私のコードオブジェクト作成が応答しない

function createAnObject(name, address) { 
      var newObj = new Object(); 
      newObj.name = name; 
      newObj.address = address; 
      newObj.saySomething = function() { 
       console.log("the name is" + this.name + " the addess is" + this.address) 
      } 
     } 


     var ballack = createAnObject('ballack', 'Ndri'); 
     console.log(ballack.name); 

ですが、コンソールにエラーが、私はここに混乱しています

Uncaught TypeError: Cannot read property 'name' of undefined 

です。誰かが私がどこに間違っているか教えてもらえますか?

+0

最初:あなたはオブジェクトを返しません。 second:Object-literalを使用し、すべてのプロパティをオブジェクトに個別に追加しないでください。 ES6、これはaddessは '関数createAnObject(名前、住所){ リターン{名前、 アドレス、 saySomething(){ はconsole.log(+ this.name + "名前は""限り短くすることができ"+ this.address); } } }「 – Thomas

答えて

1

あなたcreateAnObject機能であなたのnewObjを返すのを忘れ:

function createAnObject(name, address) { 
    var newObj = new Object(); 
    newObj.name = name; 
    newObj.address = address; 
    newObj.saySomething = function() { 
    console.log("the name is" + this.name + " the addess is" + this.address) 
    } 

    return newObj; 
}; 

var ballack = createAnObject('ballack', 'Ndri'); 
console.log(ballack.name); // Now outputs 'ballack' 
+0

ありがとうございました。私はMicrosoft 70-480の本を読んでいました。彼らは言及しませんでした。ハッ! –

+0

私はその本を知らないが、あなたは、あなたが関数から何かを返そうとするなら、関数から何かを返さなければならないと言わなかったということを意味するのだろうか? –

-1

あなたは、作成したオブジェクトを返しません。

function createAnObject(name, address) { 
      var newObj = new Object(); 
      newObj.name = name; 
      newObj.address = address; 
      newObj.saySomething = function() { 
       console.log("the name is" + this.name + " the addess is" + this.address) 
      } 

return newObj; };

 var ballack = createAnObject('ballack', 'Ndri'); 
     console.log(ballack.name); 

の作業方法上記及びここでのjsbinが働いている:http://jsbin.com/xagisanema/edit?html,js,console

+0

しかし、あなたのコードはオブジェクトを返しません。 –

+0

ありがとうございます。それを逃した。一定。 –

-1

をあなたはcreateAnObjectメソッド内newObjを返却する必要があります。

だけで、現代のJSで

return newObj; 
0

の方法の最後にリターンを追加します。

function createAnObject(name, address) { 
    return { 
    name, 
    address, 
    saySomething() { 
     console.log("the name is", this.name, "the address is", this.address); 
    } 
    }; 
} 

var ballack = createAnObject('ballack', 'Ndri'); 
console.log(ballack.name); 
関連する問題