jsFiddle Demo
“我想在一个警告消息框,我该怎么做,要显示的姓名,年龄,工作吗?”
Access中使用.name
,.age
,和.job
这样的对象上的属性: alert(person1.name+" "+person1.age+" "+person1.job);
从外部。如果你想有对象可以使用此警报,那么你可以将它像这样:
o.alertInformation = function(){ alert(this.name+" "+this.age+" "+this.job); };
function createPerson(name, age, job){
var o = new Object();
o.name = name;
o.age = age;
o.job = job;
o.sayName = function(){
alert(this.name);
};
o.alertInformation = function(){ alert(this.name+" "+this.age+" "+this.job); };
return o;
}
var person1 = createPerson('Nicholas', 29, 'Software Engineer');
var person2 = createPerson('Greg', 27, 'Doctor');
//example of accessing the object properties with dot notation
//alternatively, you could use person1["name"] to access them
alert(person1.name+" "+person1.age+" "+person1.job);
//or if you want to use an internal method on person
person1.alertInformation();
jsFiddle Demo
的Blurb的“工厂“pattern:
通常一种方法是我们在函数上调用new
关键字。当函数使用new
时,它会在函数中创建一个作用域,其中this
引用函数对象。在使用new
调用的函数内部使用this.name
将把name
附加到该对象。当您使用new
时,它会隐式地将该函数对象分配给该变量,在下面的示例中,将使用p
。
jsFiddle Demo
对于这是一个实际的工厂,请记住,它必须与实际创建的对象的参与,而不只是含蓄地返回他们。要做到这一点,我们需要一个PersonFactory(听起来很奇怪:P)。
function personFactory(){
var People = [];
var autoIncId = 0;
return {
Create: function(name,age,job){
var p = new Person(autoIncId++,name,age,job);
People.push(p);
return p;
},
GetPersonById: function(id){
return People[id];
}
};
}
其将被用于:
var pf = personFactory();
var p = pf.Create('Nicholas', 29, 'Software Engineer');
p.sayName();
p.alertInformation();
你需要调用'sayName'方法。使用'person1.sayName();' – Ian 2013-05-10 18:17:04