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("Nichaolas",23,"software Engineer");
2.构造函数模式
function Person(name,age,job){
this.name = name;
this.age = age;
this.job = job;
this.sayName = function(){
alert(this.name);
}
}
var person1 = createPerson("Nichaolas",23,"software Engineer");
//
alert(person1.constructor == Persion) ;//true
alert(person1 instanceof Object);//true
3.原型模式
/对象的原型object prototype
constructor
hasOwnPropetty
isPrototypeOf
propertyIsEnumerable
toLocaleString
toString
valueOf
每个函数都有一个prototype原型属性
function Person(){};
Person.prototype.name = "Nicholas";
Person.prototype.age = 29;
Person.prototype.job = "Software Engineer";
Person.prototype.sayName = function(){
alert(this.name);
};
var person1 = new Person();
person1.sayName();//"Nicholas"
4.组合使用构造函数模式与原型模式
function Person(name,age,job){
this.name = name;
this.age = age;
this.job = job;
this.friends = ["Shelby","Court"];
}
Person.prototype = {
constructor : Person,
sayName:function(){
alert(this.name);
}
}
var Person1 = new Person("Nocholas",23,"Software Engineer");
5.动态原型模式
function Person(name,age,job){
//属性
this.name = name;
this.age =age;
this.job = job;
//方法
if(typeof this.sayName != "function"){
Person.prototype.sayName = function(){
alert(this.name);
}
}
}
var friend = new Person("Nicholas",24,"Software Engineer");
friend.sayName();
6.寄生构造函数模式
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 friend = new Person("Nicholas",24,"Software Engineer");
friend.sayName();
//可以使用特殊的数组实现
function SpecialArray(){
//创建数组
var values = new Array();
//添加值
values.push.apply(values,arguments);
//添加方法
values.toPpedString = function(){
return this.join("|");
}
//返回数组
return values;
}
var colors = new SpecialArray("red","blue","green");
alert(colors.toPpedString());//"red|blue|green";
7.稳妥构造函数模式(没有属性)
function Person(name,age,job){
//创建要返回的对象
var o = new Object();
//可以在这里定义私有变量和函数
//添加方法
o.sayName = function(){
alert(name);
}
//返回对象
return o;
}
继承
1.原型链
实现原型链的基本模式代码:
//父类
function SuperType(){
this.property = true;
}
SuperType.prototype.getSuperValue = function(){
return this.property;
}
//子类
function SubType(){
this.subproperty = false;
}
//继承了SuperType
SubType.prototype = new SubType();
SubType.prototype.getSubValue = function(){
this.subproperty;
}
//应用
var instance = new SubType();
alert(instance.getSuperValue());//true
//对象的原型object prototype
constructor
hasOwnPropetty
isPrototypeOf
propertyIsEnumerable
toLocaleString
toString
valueOf
2.借助构造函数
function SuperType(){
this.colors = ["red","blue","green"];
}
function SubType(){
//继承了SuperType
SuperType.call(this);
}
var instance1 = new SubType();