(编辑:jimmy 日期: 2025/11/1 浏览:2)
 Number: var i = 100; i = 100.11;
 Number: var i = 100; i = 100.11; Boolean: var b = true; b = false;
 Boolean: var b = true; b = false; String: var str = 'this is a string.';
 String: var str = 'this is a string.';
    对于复杂数据类型,函数、数组和对象我们怎么办呢?函数不用说了,都是以文本方式定义的。下面就看看数组和对象是怎么表示的吧。假如我们有一个数组:
 var ary = new Array(6);
 var ary = new Array(6); ary[0] = null;
 ary[0] = null; ary[1] = 1;
 ary[1] = 1; ary[2] = 'string';
 ary[2] = 'string'; ary[3] = true;
 ary[3] = true; ary[4] = function()
 ary[4] = function() {
 { return 'keke';
     return 'keke'; };
 }; ary[5] = new MyObject();
 ary[5] = new MyObject();
    我们使用文本方式(也就是我们平时说的初始化方式)来写这个数组它将是:
 var ary1 = [null, 1, 'string', true, function(){return 'keke';}, new MyObject()];
 var ary1 = [null, 1, 'string', true, function(){return 'keke';}, new MyObject()]; 
    比上面精简的多吧?而且这里数组的文本化方式还可以写的远比这复杂的多,比如:
    第三个ary3是啥数组,我也不知道了@_@。
    不对呀,怎么ary[5]是new MyObject()呢?哦,不好意思,我们再来把MyObject示例一下,假如它被定义为:
 function MyObject()
 function MyObject() {
 { this.Properties1 = 1;
     this.Properties1 = 1; this.Properties2 = '2';
     this.Properties2 = '2'; this.Properties3 = [3];
     this.Properties3 = [3]; this.toString = function()
     this.toString = function() {
     { return '[class MyObject]';
          return '[class MyObject]'; };
     }; }
 }
 MyObject.prototype.Method1 = function()
 MyObject.prototype.Method1 = function() {
 { return this.Properties1 + this.Properties3[0];
     return this.Properties1 + this.Properties3[0]; };
 };
 MyObject.prototype.Method2 = function()
 MyObject.prototype.Method2 = function() {
 { return this.Properties2;
     return this.Properties2; };
 }; 
    那么我们的var obj = new MyObject()怎么文本化呢?其实也很简单的了,obj的文本化定义如下:
 var obj =
 var obj =  {
     { Properties1 : 1, Properties2 : '2', Properties3 : [3],
         Properties1 : 1, Properties2 : '2', Properties3 : [3], Method1 : function(){ return this.Properties1 + this.Properties3[0];},
         Method1 : function(){ return this.Properties1 + this.Properties3[0];}, Method2 : function(){ return this.Preperties2; }
         Method2 : function(){ return this.Preperties2; } };
     };
    这个类实例的直接文本化定义虽然算不上精简,但也还不错吧。这样我们就可以用这个文本化类实例去替换ary中那个new MyObject()了。类实例文本化定义的语法为,用一对"{}"表示类,也就说"{}"完全等价于"new Object()"。然后"{}"内按"key:value"组织属性和方法,key可以是任意[A-Za-z0-9_]的字符组合,甚至数字开头都是合法的@_@,value是任何的合法的文本化JavaScript数据,最后每个键值对用","来分隔就行了。