7

有没有办法可以在构造函数中完成所有这些工作?

  obj = new Object();
  obj.city = "A";
  obj.town = "B";
4

8 回答 8

16

你为什么不这样做:

var obj = {"city": "A", "town": "B"};
于 2012-08-02T12:25:30.283 回答
5

像这样:

var obj = {
    city: "a",
    town: "b"
}
于 2012-08-02T12:25:40.620 回答
5
function MyObject(params) {
    // Your constructor
    this.init(params);
}

MyObject.prototype = {
    init: function(params) {
        // Your code called by constructor
    }
}

var objectInstance = new MyObject(params);

这将是原型方式,当我需要多个对象实例时,我更喜欢使用普通对象文字。

于 2012-08-02T12:28:44.440 回答
2

试试这个

var obj = {
    city : "A",
    town : "B"
};
于 2012-08-02T12:25:53.227 回答
1
function cat(name) {
    this.name = name;
    this.talk = function() {
        alert( this.name + " say meeow!" )
    }
} 

cat1 = new cat("felix")
cat1.talk() //alerts "felix says meeow!"
于 2012-08-02T12:26:00.383 回答
1

您可以编写自定义构造函数:

function myObject(c,t) {
    this.city = c;
    this.town = t;
}

var obj = new myObject("A","B");
于 2012-08-02T13:02:16.843 回答
0

试试这个:

function MyObject(city, town) {
  this.city = city;
  this.town = town;
}

MyObject.prototype.print = function() {
  alert(city + " " + town);
}

obj = new MyObject("myCity", "myTown");
obj.print();
于 2012-08-02T12:28:53.827 回答
0

不要把事情复杂化。这是定义构造函数的最简单方法。

var Cont = function(city, town) {
           this.city = city;
           this.town = town;
          }

var Obj = new Cont('A', 'B');
于 2012-08-02T12:32:03.433 回答