您的位置:首页 > Web前端 > JavaScript

javascript 面向对象的程序设计

2012-09-20 23:07 375 查看
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);
}
}


2:构造函数mos

function Person(name, age , job){
this.name = name;
this.age = age;
this.job = job;
this.sayName = function(){
alert(this.name);
}
}


或者

function Person(name, age , job){
this.name = name;
this.age = age;
this.job = job;
this.sayName = sayName;
}
function sayName(){
alert(this.name);
}
但是这样破坏了封装性

3:原型模式:

prototype(原型),这个属性是一个对象,他的用途是包含可以由特定类型的所有实例共享的属相和方法。

function Person(){
}
Person.prototype = {
//constructor:Person,
name:"wang";
age:23;
sayName:function(){
alert(this.name);
}
};


组合构造函数和原型模式

function Person(name, age , job){
this.name = name;
this.age = age;
this.job = job;
this.friends = ["one", "two"];
}
Person.prorotype  = {
constructor:Person;
sayName : function(){
alert(this.name);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: