对象的分类: (1)内部对象:Boolean类、Number类、字符串string、Date类 【Array、Boolean、Date、Function、Global、Math、Number、Object、RegExp、String以及各类错误类对象,包括Error、EvalError、RangeError、ReferenceError、SyntaxError和TypeError】 其中Global和Math这两个对象又被称为“内置对象”,这两个对象在脚本程序初始化时被建立,没必要实例化这两个对象。 (2)宿主对象: 就是执行JS脚本的环境提供的对象。对于嵌入到网页中的JS来讲,其宿主对象就是浏览器提供的对象,因此又称为浏览器对象,如IE、Firefox等浏览器提供的对象。不一样的浏览器提供的宿主对象可能不一样,即便提供的对象相同,其实现方式也截然不同!这会带来浏览器兼容问题,增长开发难度。 浏览器对象有不少,如Window和Document等等。 (3)自定义对象:即程序员用代码本身定义的
属性是与对象相关的值。 访问对象属性的语法是:objectName.propertyName example: var obj='hello everyone!'; console.log(obj.length); 打印结果:15
方法是可以在对象上执行的动做 语法:objectName.methodName(); example: var obj='hello everyone!'; obj.toUpperCase(); 打印结果:HELLO EVERYONE
1.使用字面量直接建立程序员
example: var obj={ key:value, key:value, method:function(){ alert('I am Method'); } }
用法:obj.method();数组
2.Object构造函数建立浏览器
example: var obj= new Object(); obj.name='lucky', obj.age='18' 用法:obj();
3.使用工厂方式建立函数
example: function object(name, age, Introduction) { var o = new Object(); //建立对象 o.name = 'lucky', o.age = '18', o.Introduction = function() { alert(o.name, o.age); } return o; }
4.使用构造函数建立this
example: function Introduction(name,age,Introduction){ this.name=name; this.age=age; this.Introduction=function(){ alert('My name is' + this.name + 'My age' + this.age); } } 用法: var s1=new Introduction('Lili','16'); var s2=new Introduction('Meimei','17');
5.使用原型建立spa
example: function Proto(){} Proto.prototype.name='Lili'; Proto.prototype.age='12'; Proto.prototype.Introducte=function(){ alert(this.name); }; 用法: var s3 = new Proto();
6.组合使用构造函数和原型模式prototype
example: function Person(name,age, obj) { this.name = name; this.age = age; this.obj = obj; } Person.prototype = { constructor: Person, Introduction: function() { alert(this.name); } } 用法:var Limei = new Person('Limei','20');