function Single(){
this.name = 'single';
         _sayHello:function(){
   alert("hello world");
}
_getName:function (){
  return this.name;
}

return {
     sayHello:_sayHello,
     getName:_getName
}
}var singleObject = new Single();singleObject.sayHello();
有何不对?

解决方案 »

  1.   


    function Single(){
    this.name = 'single';
    this._sayHello = function() {
    alert("hello world");
    };
    this._getName = function() {
    return this.name;
    };

    return {
    sayHello: this._sayHello,
    getName: this._getName
    };
    }var singleObject = new Single();
    singleObject.sayHello();或者var Single = function() {
    this.name = 'single';
    };
    Single.prototype = {
    sayHello: function() {
    alert("hello world");
    },
    getName: function() {
    return this.name;
    }
    };var singleObject = new Single();
    singleObject.sayHello();
      

  2.   

        function Single() {
            this.name = 'single';
            _sayHello=function(name) {
                alert("hello world"+" "+name);
            }
            _getName=function() {
                return this.name;
            }        return {
                sayHello:_sayHello,
                getName: _getName,
                name:this.name
            }
        }    var singleObject = new Single();
        singleObject.sayHello(singleObject.getName());
      

  3.   

    1、楼主使用的是构造函数创建对象 函数体内
    _sayHello:function(){
    alert("hello world");
    }
    _getName:function (){
    return this.name;
    }
    首先这种格式是错误的  
    其次 没有将这两个方法赋到对象上 所以即使正确 _getName中的this也不指向Single对象
    1楼朋友的写法体现了js的两种不同的对象的构造方式 楼主可作参考