javascript 面向对象的程序设计

来源:互联网 发布:无神论者 知乎 编辑:程序博客网 时间:2024/05/28 23:09

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);}}




原创粉丝点击