2013-05-10 45 views
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'); 
+1

你需要调用'sayName'方法。使用'person1.sayName();' – Ian 2013-05-10 18:17:04

回答

0

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(); 
+0

这被称为工厂方法,有人使用这种模式了吗? – 2013-05-10 18:27:10

+0

@CartrightMellisa - 是的,这种模式仍然被广泛使用。虽然实施情况可能略有不同。在JavaScript中,这种模式也被称为模块模式,尽管它通常包括在函数中使用'new'关键字,而不是以您所显示的方式创建对象。 – 2013-05-10 18:29:25

+0

@CartrightMellisa - 有关创建这些对象的更常见实现的详细信息,请参阅编辑。 – 2013-05-10 18:36:01

-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(); 

这种方法被称为 '动态原型',是知道的最好方式。 我希望这可以帮助...