标签:
1.
var p=new Object();
p.name="小白";
p.sayName=function(){
alert(this.name);
}
2.字面量方式
var p={
name:"小白",
sayName:function(){
alert(this.name);
}
}
3.工厂模式
function createPerson(){
var p=new Person();
p.name="小白";
p.sayName=function(){
alert(this.name);
}
}
4.构造函数
function Person(name){
this.name=name;
this.sayName=function(){
alert(this.name);
}
}
//实例化对象
var p=new Person("小白");
5.原型模式
function Person(){
}
Person.prototype.name="小白";
Person.prototype.sayName=function(){
alert(this.name);
}
var p=new Person();
简洁写法:
function Person(){
}
Person.prototype={
name:"小白",
sayName:function(){
alert(this.name);
}
}
6.组合使用构造函数模式和原型模式
function Person(name,age){
this.name=name;
this.age=age;
}
Person.Prototype={
constructor:Person,
sayName:function(){
alert(this.name);
}
}
7.动态原型
function Person(name,age){
this.name=name;
this.age=age;
if(typeof this.sayName!="function"){
Person.prototype.sayName=function(){
alert(this.name);
}
}
}
标签:
原文地址:http://www.cnblogs.com/nook/p/4250189.html