2017-04-03 42 views
0

是否有一個JavaScript的方法來產生一個對象,例如JavaScript對象發生器功能

function newObject(name,value) { 
    // Some Awesome Logic 
    return theObject 
} 
var test = newObject('mike',32); 

,距離新對象的返回是一個對象

console.log(test); // returns an object 

{ 
    "mike": 32 
} 

我需要這樣的功能可重複使用...幫助請

+0

這是構造函數的用途。 – trincot

+0

可能只是我,但不是每次你調用它(可重用)時,構造函數都不會創建一個新對象嗎? –

+0

鑑於功能的暗示名稱,這似乎是OP想要的。 – trincot

回答

3

使用構造函數模式,關鍵字爲new,屬性名稱可以用[ ]定義:

function myObject(name,value) { 
 
    this[name] = value; 
 
} 
 
var test = new myObject('mike',32); 
 
console.log(test);

+0

工作感謝! –

1

function newObject(name, value) { 
 
    var theObject = {};  // the plain object 
 
    theObject[name] = value; // assign the value under the key name (read about bracket notation) 
 
    return theObject;  // return the object 
 
} 
 

 
var test = newObject('mike', 32); 
 

 
console.log(test);

最近ECMAScript的版本,你可以做到這一點在這樣一行:

function newObject(name, value) { 
 
    return { [name]: value }; // the key will be the value of name not "name" 
 
} 
 

 
var test = newObject('mike', 32); 
 

 
console.log(test);