//1.工厂模式
function person(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 = person('lj',22, '工人');
//2.构造函数模式
function Person(name, age, job) {
this.name = name;
this.age = age;
this.job = job;
this.sayName = function () {
alert(this.age)
}
}
var person2 = new person('lj',22, '工人');
//3.原型模式
function Person() {
}
Person.prototype.name = 'lj';
Person.prototype.age = 22;
Person.prototype.job = '工人';
Person.prototype.sayName = function () {
alert(this.name)
}
var person3 = new Person();
//3.1更简单的原型方法
function Person() {
}
Person.prototype = {
name : 'lj',
sge:22,
job:'工人',
sayName:function () {
alert(this.name)
}
}
var person3 = new Person();
//4.组合使用构造函数和原型模式(也是最常用的方法)
function PersonPrototype(name, age, job) {
this.name = name;
this.age = age;
this.job = job;
}
Person.prototype.sayName = function () {
alert(this.name)
}
var person4 = new Person('lj',22, '工人');
//5.动态原型模式
function person() {
//属性
this.name = name;
this.age = age;
this.job = job;
//方法
if(typeof this.sayName != "function"){
Person.prototype.sayName = function () {
alert(this.name)
}
}
}
var person5 = new Person('lj', 22, '工人')
//6.寄生构造函数模式
function Person(name, sge, job) {
var o = new Object();
o.name = name;
o.age = age;
o.job = job;
o.sayName = function () {
alert(this.name)
}
return o ;
}
var person6 = new Person('lj', 22, '工人');
//7.稳妥构造函数
function person (name, age, job) {
//创建要返回的对象
var o = new Object();
//可以在这里定义私有变量和函数
//添加方法
o.sayname = function () {
alert(name)
}
return o ;
}
var person7 = new Person('lj', 22, '工人');