Javascript范围问题使用JQuery Boilerplate

我正在使用JQuery Boilerplate编写我的第一个JQuery插件 – 一个响应式旋转木马。 我正在使用另一个插件(SSM – http://www.simplestatemanager.com/ )为每个设备视图创建状态。 因此,在移动设备上,functionA将运行在平板电脑上的functionB和桌面上的functionC等。

对于SSM创建的每个状态,可以添加相应的onEnter回调函数,并且在发生这种情况时我添加了3个适当的函数来运行。 从下面的代码中可以看出,onEnterDesktop函数在桌面设备上运行。 然后我尝试从这个名为createCarousel()的内部运行另一个函数,但是收到错误“createCarousel is not defined”。

我相信这是因为一个范围问题,浏览器无法从onEnterDesktop函数中找到createCarousel。 我怎样才能解决这个问题?

任何帮助都会很棒。 这是我的插件的代码:

;(function ( $, window, document, undefined ) { // Create the defaults once var pluginName = "dcResponsiveCarousel", defaults = { propertyName: "value" }; function Plugin( element, options ) { this.element = element; this.$element = $(element); this.options = $.extend( {}, defaults, options) ; this._defaults = defaults; this._name = pluginName; this.init(); } Plugin.prototype = { init: function() { ssm.addStates([ { id: 'mobile', maxWidth: 767, onEnter: this.onEnterMobile }, { id: 'tablet', maxWidth: 991, minWidth: 768, onEnter: this.onEnterTablet }, { id: 'desktop', minWidth: 992, onEnter: this.onEnterDesktop } ]); ssm.ready(); }, onEnterMobile: function (){ console.log("You've entered mobile screen dimension territory"); var itemsPerPage = 1; console.log(itemsPerPage); }, onEnterTablet: function (){ console.log("You've entered tablet screen dimension territory"); var itemsPerPage = 2; console.log(itemsPerPage); }, onEnterDesktop: function (){ console.log("You've entered desktop screen dimension territory"); var itemsPerPage = 3; createCarousel(); }, createCarousel: function (){ var $carouselItems = this.$element.children(".item"), $carouselItemsLength = $carouselItems.length, $carouselItemsWidth = 0; for (var i = 0; i < $carouselItemsLength; i++) { $carouselItemsWidth = $carouselItemsWidth + $carouselItems.eq(i).outerWidth(); }; console.log($carouselItemsWidth); this.$element } }; $.fn[pluginName] = function ( options ) { return this.each(function () { if (!$.data(this, "plugin_" + pluginName)) { $.data(this, "plugin_" + pluginName, new Plugin( this, options )); } }); }; })( jQuery, window, document ); 

它是一个对象文字,因此未定义createCarouselPlugin.prototype.createCarousel是,或者在你所在的范围内, this.createCarousel();

 onEnterDesktop: function (){ console.log("You've entered desktop screen dimension territory"); var itemsPerPage = 3; Plugin.prototype.createCarousel(); },