国内最全IT社区平台 联系我们 | 收藏本站
华晨云阿里云优惠2
您当前位置:首页 > 互联网 > Js创建对象实践

Js创建对象实践

来源:程序员人生   发布时间:2014-09-08 22:36:28 阅读次数:2784次
1.对象工具封装
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no" /> <title>testdiv</title> <script type="text/javascript" src="./../../Script/jquery.js"></script> </head> <body> <a href="javascript:void" id="showdiv">sssss</a> </body> <script> var ss = {}; ss.tools = function(){ var a=1; var b=2; return{ aaa:a, show_1:function(){ return a+b; }, show_2:function(){ return a-b; }, } }(); $("#showdiv").click(function(){ var xx = ss.tools.show_1(); alert(xx); var xx2 = ss.tools.show_2(); alert(xx2); }) </script> </html>


2.工厂模式
function createPerson(name,age,job){ var o = { name:name, age:age, job:job, sayName:function(){ alert(this.name); } }; return o; }; var wyz1 = createPerson("wyz","30","female"); var wyz2 = createPerson("wyz2","30","male"); wyz1.sayName(); wyz2.sayName();




3.构造函数模式 this
function MathFunc(a,b) { this.a = a; this.b = b; this.add = function() { return a+b; } } var add = new MathFunc(3,4); var sum = add.add(); alert(sum);


4.?Apply和call?
function MathFunc(a,b) { this.a = a; this.b = b; this.add = function() { return a+b; } } var myadd={}; //MathFunc.call(myadd,31,4); MathFunc.apply(myadd,[31,4]); var sum = myadd.add(); alert(sum);


5.原型共享方法
function MathFunc(a,b) { this.a = a; this.b = b; MathFunc.prototype.add = function() { return a+b; } }; var myadd= new MathFunc(3,4); var sum = myadd.add(); alert(sum);


生活不易,码农辛苦
如果您觉得本网站对您的学习有所帮助,可以手机扫描二维码进行捐赠
程序员人生
------分隔线----------------------------
分享到:
------分隔线----------------------------
关闭
程序员人生