有没有办法可以在构造函数中完成所有这些工作?
obj = new Object();
obj.city = "A";
obj.town = "B";
你为什么不这样做:
var obj = {"city": "A", "town": "B"};
像这样:
var obj = {
city: "a",
town: "b"
}
function MyObject(params) {
// Your constructor
this.init(params);
}
MyObject.prototype = {
init: function(params) {
// Your code called by constructor
}
}
var objectInstance = new MyObject(params);
这将是原型方式,当我需要多个对象实例时,我更喜欢使用普通对象文字。
试试这个
var obj = {
city : "A",
town : "B"
};
function cat(name) {
this.name = name;
this.talk = function() {
alert( this.name + " say meeow!" )
}
}
cat1 = new cat("felix")
cat1.talk() //alerts "felix says meeow!"
您可以编写自定义构造函数:
function myObject(c,t) {
this.city = c;
this.town = t;
}
var obj = new myObject("A","B");
试试这个:
function MyObject(city, town) {
this.city = city;
this.town = town;
}
MyObject.prototype.print = function() {
alert(city + " " + town);
}
obj = new MyObject("myCity", "myTown");
obj.print();
不要把事情复杂化。这是定义构造函数的最简单方法。
var Cont = function(city, town) {
this.city = city;
this.town = town;
}
var Obj = new Cont('A', 'B');