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