JS是一门面向对象语言,其对象是用原型属性来模拟的,下面,来看看如何封装JS对象。
常规封装
function Person (姓名、年龄、性别){,,,this.name =,名字,,,,,this.age =,年龄,,,,,this.sex =,性; } Pserson.prototype =,{,,,构造函数:人, ,,,sayHello:函数(){,,,,,,,console.log(“你好”); ,,,} }
这种方式是比较常见的方式,比较直观,但()是人的职责是构造对象,如果把初始化的事情也放在里面完成,代码就会显得繁琐,如果放在一个方法里初始化会不会好点呢?
升级版(常见)
function Person (信息){,,,this._init_(信息); } Pserson.prototype =, {,,, constructor :,人, ,,,_init_ :,函数(信息),{,,,,,,,this.name =, info.name;,,,,,,,, this.age =, info.age;,,,,,,,, this.sex =, info.sex; ,,,} ,,,sayHello:函数(){,,,,,,,console.log(“你好”); ,,,} }
可是,说到这里就发现,姓名,年龄,性别并没有在人里面申明,哪来的呢? ? ?
新的执行原理
新的执行过程可以用下面一个函数来代替
<>之前,,,,var myNew =,函数(构造函数,,args), { ,,,,,,,var o =, {}; ,,,,,,,o.__proto__ =, constructor.prototype;,,,,,,,, var res =, constructor.apply (o, args);,,,,,,,, var type =, typeof res,,,,,,,,, if ([“字符串”,“数量”,“布尔”,“空”,“定义”).indexOf(类型),!==,1),{ ,,,,,,,,,,,return o; ,,,,,,,} ,,,,,,,return res; ,,,}解释:
首先通过var o={}构造一个空对象。
然后将构造函数的原型属性原型赋值给o的原型对象__proto__。这样,在执行this.init(信息);这句话的时候,对象o就可以在其原型对象中查找_init_方法。(原型链)。
之后这句话就是精髓了。
var res =, constructor.apply (o, args);
以o为上下文调用函数,同时将参数作为数组传递,那么,
<>之前,this._init_(信息),这句话就会被阿执行,
函数
以o为上下文调用,o也将拥有自己的名字,年龄,性属性。
如果在构造函数中,返回复合类型,包括对象,函数,和正则表达式,那么就会直接返回这个对象,否则,返回o。
<>之前,var type =, typeof res,,,,,如果([“字符串”,“数量”,“布尔”,“空”,“定义”).indexOf(类型),!==,1){,,,,,,,return o; ,,,},,,,return res;测试一下
<前> ,,,function 人(名字),{,,,,,,,this.name =,名称; ,,,} ,,,Person.prototype.sayHello =,()函数,{,,,,,,,console.log (this.name); ,,,},,,,var o1 =, myNew(人,[‘兵’]),,,,,console.log (o1群); ,,,o1.sayHello ();
好吧
类jQuery封装
这种方式是我从jQuery那里学来的。
jQuery对象具有很强的集成性,可以作为函数调用,也可以做为对象调用,当作为函数调用的时候,她可以无需新而返回它的一个实例,很方便。
先看代码
var Person =,函数(信息){,,,return new Person.prototype.init(信息); } Person.prototype =,{,,,构造函数:,人, ,,,init:函数(){,,,,,,,this.name =, info.name。 ,,,} } Person.prototype.init.prototype =, Person.prototype;
这种封装方式非常巧妙。
将对象的构造操作放在函数的里面,而自己充当一个工厂。
不断调用原型并不是一个直观的做法,于是
var Person =,函数(信息){,,,return new Person.fn.init(信息); } 时间==Person.fn Person.prototype {,,,构造函数:,人, null null null null null null null null null null null null null null null null null null null null null null null null null null null nullJS对象封装的常用方式