1

我想在警告消息框中显示姓名、年龄、工作,我该怎么做?

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');
4

2 回答 2

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

模糊“工厂”模式:

通常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();
于 2013-05-10T18:17:01.710 回答
-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();

这种方法称为“动态原型”,是最好的方法。我希望这可以帮助...

于 2013-05-10T18:44:05.660 回答