2016-11-16 77 views
0

不知道一个对象是我想要的,但我想创建类似这样的东西。Javascript对象查询

var thing = {a: 0, b: 0}; 
function fun() { 
    var mything = new thing(); 
    mything.a = 5; 
    mything.b = 7; 
    return mything; 
} 
var another = fun(); 

然后我可以在我的代码中使用another.a和another.b。我在JavaScript中工作,并且对此很新。我知道在另一种语言中,我会创建一个结构,但不知道如何去做。 在此先感谢。

+0

所以,你想要什么,因为现在我不理解你。 –

回答

0

我相信function是你想要的。请这个评论之一:

function thing() { 
 
    if (!(this instanceof thing)) { 
 
    return new thing(); 
 
    } 
 
    //properties with default value 
 
    this.a = 5; 
 
    this.b = 7; 
 
    return this; 
 
} 
 

 
//and you can call it either like this 
 
var foo = thing(); 
 
//or like this 
 
var bar = new thing(); 
 

 
//and both you can define their dependent property like this 
 
foo.a = 123; 
 
foo.b = 345; 
 

 
bar.a = "not number1"; 
 
bar.b = { 
 
    other: "result" 
 
} 
 
console.log(foo, bar);

0

你需要使用类语法(ES6)或函数的构造函数来定义Thing

// Using ES6 syntax 

class Thing { 
    constructor() { 
    this.a = 5; 
    this.b = 7; 
    } 

    foo() { 
    // thing instance method (`this` === current instance) 
    } 
} 

// OR Using classic constructor syntax 

function Thing() { 
    this.a = 5; 
    this.b = 7; 
} 

Thing.prototype.foo = function() { 
    // thing instance method (`this` === current instance) 
}; 

您可以创建后/分配新的实例使用new

var thing = new Thing(); 

或者还有包裹它使用工厂方法,例如:

// ES6 syntax 
class Thing { 
    // ... 
    static create() { 
    return new Thing(); 
    } 
} 

// Or attaching to Thing 
Thing.create = function factory() { 
    return new Thing(); 
} 

,把它:

var things = Thing.create();