我想在這裏創建一個新的對象。 這裏是我的代碼對象創建沒有響應
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
我很困惑在這裏。有人能告訴我我哪裏出錯了。
第一:你不回的對象。第二:使用Object-literal,並且不要將每個屬性單獨添加到對象。在ES6中,這可能與'function createAnObject(name,address)一樣短'{ 返回{ 名稱, 地址, saySomething(){「{」名稱是「+ this.name +」)這個地址是「+ this.address); } } }' – Thomas