JavaScript在匿名函数内返回匿名函数

时间:2014-04-21 20:43:05

标签: javascript anonymous-function

为什么getNameFun返回了一个匿名函数(参见segment1),它是否可以返回this.name(参见segment2)?

SEGMENT1:

var name = "The Window";
  var object = {
    name : "My Object",
    getNameFunc : function(){
      return function(){
        return this.name;
      };
    }
  };
  alert(object.getNameFunc()());

分段2:

var name = "The Window";
  var object = {
    name : "My Object",
    getNameFunc : function(){
      
        return this.name; // different is here!
      
    }
  };
  alert(object.getNameFunc());

1 个答案:

答案 0 :(得分:0)

以这种方式试试

 var myclass = function(){
     var self = this;
     self.Name = "My Object";

    self.getNameFunc = function(){ return self.Name;}
}

var myc = new myclass();
alert(myc.getNameFunc());

这是帮助

的小提琴

http://jsfiddle.net/AqdQG/