李刚JavaScript视频学习-对象

来源:互联网 发布:淘宝好的男装店铺 编辑:程序博客网 时间:2024/05/29 12:48
JS创建对象的几种方法
1、通过new关键字,调用构造器创建
2、通过new Object(),再给对象赋属性方法
3、使用JSON语法(JavaScript Object Notation)
JSON {}:代表对象 []:代表数组

/.../正则表达式


<html><head></head><body><!--JS创建对象的几种方法1、通过new关键字,调用构造器创建2、通过new Object(),再给对象赋属性方法3、使用JSON语法(JavaScript Object Notation)JSON {}:代表对象 []:代表数组/.../正则表达式--><script type="text/javascript">function Person(name ,age){this.name=name;this.age=age;Person.eyeNum=2;}Person.prototype.info=function(){alert("我的信息是:"+this.name+"->"+this.age);};var p1=new Person("孙悟空",500);var p2=new Person("猪八戒",500);p1.info();p2.info();//JS并没有严格的类继承关系//JS类只有两层,所有的都继承自Object//JS是动态语言,对象的属性、方法可以动态改变,JS对象在内存中占有的地址可以变化alert(p1 instanceof Person);var o=new Object();alert(o.toString());o.name="孙悟空";o.age=500;alert(o.name+"->"+o.age);o.info=function(){alert("我的信息是:"+o.name+"->"+o.age);}o.info();alert("---------------------")o.info.call(window);var str="var d=200; alert(d);"eval(str);var obj=[];alert(obj.length);obj[100]='张三';alert(obj.length)obj[5]={name : "小聪",age : 10,walk : function(){alert("慢慢地走");},parents : [{name : "阿坤",age : 35},{name : "阿迅",age : 34}]}alert(obj[5].name);alert(obj[5].parents[0].name);obj[5].walk();</script></body></html>

JS如何定义类
JS在定义函数的时候就定义了一个类,并创造了类的构造器
JS继承
1、JS继承由关键字prototype实现;
2、JS功能上的子类与功能上的父类具有相同的名字
3、可以为系统增加新的功能


<html><head></head><body><script src="myPrototype.js" type="text/javascript"></script><!--JS如何定义类JS在定义函数的时候就定义了一个类,并创造了类的构造器JS继承1、JS继承由关键字prototype实现;2、JS功能上的子类与功能上的父类具有相同的名字3、可以为系统增加新的功能JS创建对象的几种方法1、通过new关键字,调用构造器创建--><script type="text/javascript">function Person(name ,age){this.name=name;this.age=age;Person.eyeNum=2;/*易造成内存泄漏,JS每创建一个person对象,内存中会创建一个新的函数*//*this.info=function(){alert("我的信息是"+this.name+"->"+this.age);};*/}//如果要为类创建方法,采用关键字 prototypePerson.prototype.info=function(){alert("我的信息是:"+this.name+"->"+this.age);};var p1=new Person("孙悟空",500);var p2=new Person("猪八戒",500);p1.info();p2.info();Person.prototype.run=function(){alert(this.name+"跑得好快啊!");};p1.run();p2.run();var arr=[2,5,8];alert(arr.length);arr.each(function(index,ele){alert(ele);});var newArr=arr.map(function(index,ele){return ele*ele*ele;});alert(newArr); alert(arr.map(function(index,ele){return Math.sqrt(ele);}));alert("=========="+"           abc             "+"-------".trim());</script></body></html>

Array.prototype.each=function(fn){for(var i=0,len=this.length;i<len;i++){fn.call(null,i,this[i]);}};Array.prototype.map=function(fn){var result=new Array(this.length);for(var i=0,len=this.length;i<len;i++){result[i]=fn.call(this,i,this[i]);}return result;};/*正则表达式 空白\s 不是空白\S   数字\n 不是数字\N   字母\w 不是字母\W   .任意字符*/String.prototype.trim=function(){return this.replace(/^\s+/ ,"").replace(/\s+$/,"").replace(/\s/,"");};



0 0
原创粉丝点击