调用函数内部的原型方法不起作用
Calling prototype method inside function not working
我正在尝试使用Javascript和jQuery创建一个库类。
我有一些库类的原型函数,但当我试图访问类内的这些函数时,它显示了错误
Uncaught TypeError: Gallery.start is not a function
我的JSfiddle链接
这是我的Javascript:
/**
*
* @param options should be object of following
* options.images Array of gallery images URL
* options.start slide starting point
* options.autoPlay This option will be false by default
*
*/
function Gallery(options) {
var _this = this;
var galleryOptions = options;
function randomString(len, charSet) {
var ranString = '';
var randomPoz;
charSet = charSet || 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
for (var i = 0; i < len; i++) {
randomPoz = Math.floor(Math.random() * charSet.length);
ranString = ranString + charSet.substring(randomPoz, randomPoz + 1);
}
return ranString;
}
function addThumbnail(imgSrc) {
return '<li class="thumbnail__list"><img src="' + imgSrc + '" class="thumbnail__list-img" /></li>';
}
function renderThumbnail(imgArr) {
var html = [];
if (imgArr) {
$.each(imgArr, function(i, v) {
html.push(addThumbnail(v));
});
}
return '<ul class="gallery__thumbnail__container">' + html.join('') + '</ul>';
}
function getPlaceholder() {
return 'dummy.jpg';
}
function disableNext(thisObj) {
thisObj.galleryElement.find('.next').addClass('disabled');
}
function disablePrev(thisObj) {
thisObj.galleryElement.find('.prev').addClass('disabled');
}
function enableNext(thisObj) {
thisObj.galleryElement.find('.next').removeClass('disabled');
}
function enablePrev(thisObj) {
thisObj.galleryElement.find('.prev').removeClass('disabled');
}
function togglePrevNext(self) {
if (self._opt.currIndex === (self._opt.imagesLength)) {
disableNext(self);
} else {
enableNext(self);
}
if ((self._opt.currIndex - 1) === 0) {
disablePrev(self);
} else {
enablePrev(self);
}
}
function controls() {
var html = [];
html.push('<div class="prev sz-icon-arrow-left"></div>');
html.push('<div class="next sz-icon-arrow-right"></div>');
return '<div class="gallery__controls">' + html.join('') + '</div>';
}
function bindClickEvents(galleryElement) {
galleryElement.on('click', '.start', function() {
_this.start();
});
galleryElement.find('.stop').on('click', function() {
_this.stop();
});
galleryElement.find('.prev').on('click', function() {
_this.prev();
});
galleryElement.find('.next').on('click', function() {
_this.next();
});
galleryElement.find('.thumbnail__list').on('click', function() {
_this.goTo(Number($(this).index()) + 1);
});
}
function checkOptions(option) {
var opt = option;
opt.images = (opt.images.length) ? opt.images : getPlaceholder();
opt.thumbnail = (opt.thumbnail) ? true : false;
opt.fullScreen = (opt.fullScreen) ? true : false;
opt.container = (opt.fullScreen) ? 'body' : opt.container;
opt.container = (opt.container) ? opt.container : 'body';
opt.autoPlay = (opt.autoPlay) ? true : false;
opt.start = (opt.start && opt.start <= Number(opt.images.length)) ? opt.start : 1;
return opt;
}
Gallery.init = function() {
var html;
_this._opt = checkOptions(galleryOptions);
_this._opt.imagesLength = Number(_this._opt.images.length);
_this._opt.currIndex = Number(_this._opt.start);
_this._opt.elementName = 'gallery--' + randomString(5, 'SZgallery');
if (_this._opt.fullScreen) {
html = '<div class="pop-up__model ' + _this._opt.elementName + '">' +
'<div class="pop-up__model-table">' +
'<div class="pop-up__model-cell">' +
'<div class="gallery"><div class="pop-up__model-content">' +
'<div class="gallery__inner-wrapper"></div>' +
'</div></div>' +
'</div></div>' +
'</div>';
$(_this._opt.container).append('', html);
if (_this._opt.thumbnail) {
$('.pop-up__model-content').append('', '<div class="thumbnail__list-wrapper">' + renderThumbnail(options.images) + '</div>').append('', controls());
}
} else {
$(_this._opt.container).append('', '<div class="gallery gallery--hidden ' + _this._opt.elementName + '"></div>');
}
_this.galleryElement = $('.' + _this._opt.elementName);
if (_this._opt.fullScreen) {
_this.galleryElement.find('.gallery__inner-wrapper').append('', '<div class="gallery__img-holder">' +
'<img class="gallery__img-preview" src="' + _this._opt.images[_this._opt.start - 1] + '"/>' +
'</div>');
} else {
_this.galleryElement.append('', '<div class="gallery__img-holder">' +
'<img class="gallery__img-preview" src="' + _this._opt.images[_this._opt.start - 1] + '"/>' +
'</div>');
}
if (_this._opt.thumbnail) {
_this.galleryElement.append('', renderThumbnail(options.images)).append(controls());
} else {
_this.galleryElement.append('', controls());
}
if (_this._opt.autoPlay) {
Gallery.start();
}
bindClickEvents(_this.galleryElement);
};
Gallery.prototype = {
start: function() {
_this.goTo(_this._opt.currIndex);
_this.galleryElement.removeClass('gallery--hidden');
console.log('started', _this._opt);
if (_this._opt.fullScreen) {
$('.pop-up__model').addClass('is_visible');
}
},
stop: function() {
_this.galleryElement.addClass('gallery--hidden');
},
next: function() {
if (_this._opt.currIndex <= (_this._opt.imagesLength - 1)) {
_this._opt.currIndex++;
_this.goTo(_this._opt.currIndex);
}
},
prev: function() {
if ((_this._opt.currIndex - 1) !== 0) {
_this._opt.currIndex--;
_this.goTo(_this._opt.currIndex);
}
},
goTo: function(imgNo) {
var thumbnail;
_this._opt.currIndex = Number(imgNo);
if (_this._opt.images[imgNo - 1]) {
_this.galleryElement.find('.gallery__img-preview').attr('src', _this._opt.images[imgNo - 1]);
}
if (_this._opt.thumbnail) {
thumbnail = _this.galleryElement.find('.thumbnail__list');
thumbnail.removeClass('active');
thumbnail.eq(imgNo - 1).addClass('active');
}
togglePrevNext(_this);
},
destroy: function() {
console.log('destroyed');
}
};
return Gallery;
}
var imgArr = ['images/placeholder-1.png', 'images/placeholder-2.png', 'images/placeholder-3.jpg', 'images/placeholder-4.jpg'];
var hotelPhotosGallery = new Gallery({
images: imgArr,
autoPlay: true,
container: '.photo-list'
});
hotelPhotosGallery.init();
在查看了您的代码后,我发现了问题:
if (_this._opt.autoPlay) {
Gallery.start(); // This method doesn't exist on a non instantiated object
}
您试图调用函数本身的方法,而不是该函数实例原型上的方法(使用new
实例化)。
但是,原型方法在非实例化项上不可用,因为函数中的this
默认情况下会附加到全局对象。当使用new
时,该this
实际上成为一个新对象,并从function
隐式返回,从而创建一个新实例。关于使用函数构造函数的更多信息
通常,这将通过使用上下文(即this
)而不是函数名来解决
if (_this._opt.autoPlay) {
this.start(); // Use the context of the instantiated Gallery
}
然而,在您的特定情况下,您正在重新定义原型:
Gallery.prototype = { ... } // You are overwriting the prototype object
而不是使用JS引擎已经为您准备好的,并在上面添加方法:
// add methods directly on the prototype
Gallery.prototype.method1 = // ...
Gallery.prototype.method2 = // ...
这种方式是潜在的不安全,因为在重新定义原型之前,它最终会删除原型中存在的任何其他内容。
如果您不关心这一点,并且希望保持代码的原样,您也可以通过显式调用原型来访问您的方法:
if (_this._opt.autoPlay) {
Gallery.prototype.start(); // Explicitly call the prototype, since you already defined it
}
您没有正确调用它。如果你需要调用原型函数,它必须像一样
Gallery.protype.start()
如果您试图实现一个特殊的行为(基于对象的),那么它应该是这样的。这里还有一些在JavaScript 中模拟类的不同方法
相关文章:
- Meteor-添加用户自定义字段的方法不起作用
- 在 JQUERY 中创建 HTML 后,Jquery 方法不起作用
- 为什么这个扩展方法不起作用
- Splice()方法不起作用
- Angularjs-向工厂传递数据的方法不起作用
- Knockout和bread.js的take方法不起作用Paging
- javascript注入$http-post方法不起作用
- 为什么pulk()和where()方法不起作用
- Ajax get 方法不起作用
- 当我将javascript代码放在外部站点.js文件中时,Ajax页面方法不起作用
- getJSON 方法不起作用
- Jquery ajax get 方法不起作用
- jQuery AddClass 方法不起作用
- ScriptManager.RegisterStartupScript() 方法不起作用 - ASP.NET,C#
- 为什么JavaScript方法不起作用
- 为什么 findRandom() mongoose for node.js 方法不起作用
- BackboneJS的设置方法不起作用
- 从javascript调用 asp.net 页面方法不起作用
- 主干.js对以前的方法不起作用进行建模
- toExponential() 方法不起作用