JS-[factory mode the prototype & Constructors &]

 

 

Factory Pattern

To create an object by a function (factory function)

function createPerson(name,age){
	var obj={
		name:name,
		age:age,
		setName:function(name){
			this.name=name;
		}
	};
	return obj;	//return一个object
}
createPerson("sam",20);

Custom Constructor

function Person(name,age){	//构造函数首字母要大写
	this.name=name;
	this.age=age;
	this.setName=function(name){
		this.name=name;
	};
}
var person1=new Person("sam",20);

And the difference between factory model constructor

  • Object is an object factory mode returns, there is no particular type
  • When the constructor returns a particular type of object

protorype use

Statement did not declare property

Person.prototype.phone=null;	//接上面代码,在Person没有phone的情况下用peototype声明
var person2=new Person("jack",21);
person2.phone="25698546";
alert(person2.phone);	//正常输出

Dynamic method statement

function Person(name,age){	
	this.name=name;
	this.age=age;
	this.say=function(){
		alert("miao~");
	};
}
var p1=new Person("sam",20);
p1.say();

miao say only in the case of the above - can be used prototype

function Person(name,age){
	this.name=name;
	this.age=age;
	//先不写say方法
}

Person.prototype.say=null;	//声明say方法

var p1=new Person("sam",20);
p1.say=function(){	//设置p1的say方法
 alert("miao~");
};
p1.say();

var p2=new Person("gou",2);
p2.say=function(){	//设置p2的say方法
 alert("wang~");
};
p2.say();

Guess you like

Origin www.cnblogs.com/yangjiale/p/11261379.html
Recommended