2016-05-08 71 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

第一:你不回的對象。第二:使用Object-literal,並且不要將每個屬性單獨添加到對象。在ES6中,這可能與'function createAnObject(name,address)一樣短'{ 返回{ 名稱, 地址, saySomething(){「{」名稱是「+ this.name +」)這個地址是「+ this.address); } } }' – Thomas

回答

1

你忘了回報您newObjcreateAnObject功能:

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

謝謝..好吧,我正在讀微軟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

你必須返回newObjcreateAnObject方法內。

只是在方法的末尾添加回報,

return newObj; 
0

在現代JS:

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);