JS构造函数与原型

来源:互联网 发布:来自新世界知乎 编辑:程序博客网 时间:2024/06/05 21:09
// 工厂方式function createPerson(name,sex) {    //原料    var obj = new Object();    //加工    obj.name = name;    obj.sex = sex;    obj.showName = function () {        alert(this.name);    };    obj.showSex = function () {        alert(this.sex);    };    //出厂    return obj;};var p1 = createPerson("blue","");var p2 = createPerson("leo","");p1.showName()  // bluep2.showSex()   // alert(p1.showName==p2.showName)   // false   此时每新创建一个对象,它都是重新创建自己的showName方法// 用工厂方式构造函数function createPerson(name,sex) {    //此处可以假想有  var this = new Object();    this.name = name;    this.sex = sex;    this.showName = function () {        alert(this.name);    };    this.showSex = function () {        alert(this.sex);    };    //此处可以假想有  return this;};var p1 = new createPerson("leo","");var p2 = new createPerson("blue","");p1.showSex()   //p2.showName()  // bluealert(p1.showName==p2.showName)    // false   此时同上//用原型构造函数 (如系统常用的类:new Date(),new Image()..)function CreatePerson(name,sex) { //将不同的属性放在函数内    this.name = name;    this.sex = sex;};CreatePerson.prototype.showName = function () { //将相同的方法放在函数外    alert(this.name);};CreatePerson.prototype.showSex = function () {    alert(this.sex);};var p1 = new CreatePerson("leo","");var p2 = new CreatePerson("blue","");p1.showSex()   //p2.showName()  // bluealert(p1.showName==p2.showName)   //true  此时所有创建出来的新对象都是使用原型中方法,是同一个//关于原型的优先级问题Array.prototype.a = 12;var arr = new Array(1,2,3);alert(arr.a)   // 12  从原型中读取的//给对象添加属性arr.a = 5;alert(arr.a)   // 5  直接给对象添加的属性覆盖原型中的属性//删除给对象添加的属性delete arr.a;alert(arr.a)   // 12  删除直接给对象添加的属性后,原型中的属性就又出来了//总结: 给原型添加方法,相当于给一类对象添加;给对象添加方法,只是对单一对象添加的,他们之间的关系类似于CSS中的类样式与行间样式的关系
原创粉丝点击