俺觉得 LZ 的问题不是风格问题,而是基本概念不清的问题!风格1 是普通的函数定义,风格2 是一种对象定义,当然 风格1 也可以定义对象,LZ 还是找本书先看看基本概念吧,JS 并不像看起来那么简单!

解决方案 »

  1.   

    谢谢,一楼的回答,这两个的区别我是明白的,其实这两种类型的定义也是可以相互转变的,对吗?我只是尝试了从函数定义变换为对象定义,在html的使用中就出了错,是这个问题让我有些困惑了
    请细说下,谢谢!
      

  2.   

    刚用关键字搜索了下js 面向对象,的确是能找到上面风格2的代码定义发,才发现这个js的代码风格还真的是比较随意,呵呵,学习中了!
    下面把看到的能给我提示的内容贴上,希望大家也能受用,一共给了5种写法,唉也不知道这个语言怎么有了这么多的定义方法,严格遵守一种多方便,搞不懂了,怎么也没有一个规范,可能还是我浮浅了 :(
     JS 中面向对象写法 
    //定义Circle类,拥有成员变量r,常量PI和计算面积的成员函数area()
    ///////////////////// 1 //////////////////////////////////////
    function Circle(r) {
          this.r = r;
    }Circle.PI = 3.14159;
    Circle.prototype.area = function() {
     return Circle.PI * this.r * this.r;
    }var c = new Circle(1.0);   
    alert(c.area()); 
    ////////////// 2 /////////////////
    var Circle = function() {
       var obj = new Object();
       obj.PI = 3.14159;
       
       obj.area = function( r ) {
           return this.PI * r * r;
       }
       return obj;
    }var c = new Circle();
    alert( c.area( 1.0 ) );
    //////////// 3 ///////////////////
    var Circle = new Object();
    Circle.PI = 3.14159;
    Circle.Area = function( r ) {
           return this.PI * r * r;
    }alert( Circle.Area( 1.0 ) );
    ///////////// 4 /////////////////
    var Circle={
     "PI":3.14159,
     "area":function(r){
      return this.PI * r * r;
     }
    };
    alert( Circle.area(1.0) );
    //////////////// 5 //////////////////
    var Circle = new Function("this.PI = 3.14159;this.area = function( r ) {return r*r*this.PI;}");
    alert( (new Circle()).area(1.0) );
      

  3.   

    终于把风格1的代码改造成风格2的代码,也发现这两个编码思想差别好大,风格1完全面向过程,风格2有些类似java的面向对象,但也不是完全的一致,这个有些说不好了,一个感觉,要使用对象newformat里面的方法和共有变量,必须是要通过类名才可以引用到,这个在风格1里面是不需要的,其实可能问题就是这么简单
    把改造好的js贴上,给今天一个总结了,呵呵
    var newformat = {
            x: null,
            y: null,
            mousedown : function(obj)
            {
                obj.onmousemove = newformat.mousemove;
                obj.onmouseup = newformat.mouseup;
                
                oEvent = window.event ? window.event : event;
                
                this.x = oEvent.clientX;
                this.y = oEvent.clientY;
            },
            
            mousemove : function()
            {
                var temp = newformat;
                
                oEvent = window.event ? window.event : event;
               
                var top = oEvent.clientY - temp.y + parseInt(this.style.top) + "px";
                var left = oEvent.clientX - temp.x + parseInt(this.style.left) +"px";
                
                this.style.top = top;
                this.style.left = left;
                temp.x =  oEvent.clientX;
                temp.y =  oEvent.clientY
            },
            
            mouseup : function ()
            {
                this.onmousemove = null;
                this.onmouseup = null;
            }
    };