2012-12-04 72 views
0

为什么它不工作,它说它不是一个函数,为什么我不能从myalert2调用myalert()?怎么做??如何调用内部函数?

var sheepclass = function(handler) { 
    this.handler = $.extend({ 
     'sizes': 'thin', 
     'eat': 'grass', 
     'color': 'white', 
     myalert: function() { 
      alert('Hello World'); 
     }, 
     myalert2: function() { 
      handler.myalert(); 
      this.handler.myalert(); //this not work either 
     } 
    }, handler); 
} 
var blacksheep = new sheepclass({ 
    'color': 'black' 
}); 
blacksheep.handler.myalert2(); 

回答

0

这是因为范围的...

http://jsfiddle.net/78QXc/

var sheepclass = function(handler) { 
    this.handler = $.extend({ 
     'sizes': 'thin', 
     'eat': 'grass', 
     'color': 'white', 
     myalert: function() { 
      alert('Hello World'); 
     }, 
     myalert2: function() { 
      this.myalert(); 
     } 
    }, handler); 
} 
var blacksheep = new sheepclass({ 
    'color': 'black' 
}); 
blacksheep.handler.myalert2();​ 
0

只需拨打this.myalert()会做

+0

哇,是的,为什么呢?它应该是handler.something,我把所有内部变成handler.size,hander.xxx()然后我必须将它们全部更改为...奇怪... – FatDogMark

+0

您正在扩展处理程序对象,并且'this'实际上指的是处理程序对象本身。所以你不必编写'this.handler'。 – Stanley