我想在警告信息框中显示姓名,年龄,工作,我该怎么办?
function createPerson(name, age, job) {
var o = new Object();
o.name = name;
o.age = age;
o.job = job;
o.sayName = function () {
alert(this.name);
};
return o;
}
var person1 = createPerson('Nicholas', 29, 'Software Engineer');
var person2 = createPerson('Greg', 27, 'Doctor');
答案 0 :(得分:0)
的 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
强> 的
Blurb on“factory”模式:
通常使用在函数上调用new
关键字的方法。在函数上使用new
时,它会在this
引用函数对象的函数中创建范围。在使用this.name
调用的函数内使用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();
答案 1 :(得分:-1)
function createPerson(name, age, job){
this.name=name;
this.age=age;
this.job=job;
if(createPerson._intialized=="undefined"){
createPerson.prototype.sayPersonInfo=function(){
alert('i am '+this.name+' , '+this.age+'years old and my job is '+this.job);
}
createPerson._initialized=true;
}
var person1 = createPerson('Nicholas', 29, 'Software Engineer');
var person2 = createPerson('Greg', 27, 'Doctor');
person1.sayPersonInfo();
这种方法被称为“动态原型”,是知道的最佳方式。 我希望这可以帮助...