jsFiddle Demo
“我想在警告消息框中显示姓名、年龄、工作,我该怎么做?”
.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
模糊“工厂”模式:
通常new
在函数上调用关键字的地方使用一种方法。当new
在函数上使用时,它会在函数中创建一个作用域,其中this
引用函数对象。this.name
在调用 with 的函数内部使用将new
附加name
到对象。当您使用new
时,它会隐式地将函数对象分配给变量,在下面的示例中,p
使用的是。
function Person(name, age, job){
this.name = name;
this.age = age;
this.job = job;
}
Person.prototype.sayName = function(){
alert(this.name);
};
Person.prototype.alertInformation = function(){
alert(this.name+" "+this.age+" "+this.job);
};
var p = new Person('Nicholas', 29, 'Software Engineer');
p.sayName();
p.alertInformation();
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();