工厂模式创建对象、构造函数和原型模式
2018-12-05 本文已影响0人
姓高名旭升
1.工厂模式
function Person(name,age,job) {
//创建一个空对象
var o = {};
o.name = name;
o.age = age;
o.job = job;
o.showName = function () {
alert(this.name);
};
o.showName = function () {
alert(this.age);
};
o.showName = function () {
alert(this.job);
};
return o;
}
var Tom = Person('tom',18,'程序员');
Tom.showName();
2.构造函数
function Person(name,age,job) {
this.name = name;
this.age = age;
this.job = job;
this.showName = function () {
alert(this.name);
};
this.showAge = function () {
alert(this.age);
};
this.showJob = function () {
alert(this.job);
};
}
var Bob = new Person('bob',18,'产品汪');
Bob.showName();
3.原型模式
function Person(name,age,job) {
this.name = name;
this.age = age;
this.job = job;
}
// prototype原型
Person.prototype.showName = function () {
alert(this.name);
};
Person.prototype.showAge = function () {
alert(this.age);
};
Person.prototype.showJob = function () {
alert(this.job);
};
var Lucy = new Person('Lucy',19,'测试鼠');
alert(Lucy.showName());