首页 > 这个JS原型方法怎么写

这个JS原型方法怎么写

想要写一个分页类,把它加到原型中

function PaginationHelper(collection, itemsPerPage){
}
PaginationHelper.prototype.itemCount = function() {
   return Math.floor(collection.length/itemsPerPage)
}
var helper = new PaginationHelper(['a','b','c','d','e','f'], 4);

helper.itemCount(); 

为啥会报错?


因为你构造函数传入的参数,原型接收不到,就报错了。
可以直接在原型的方法中传入参数。
function PaginationHelper() {};
PaginationHelper.prototype.itemCount = function (collection, itemsPerPage) {

return Math.floor(collection.length / itemsPerPage);

};
var helper = new PaginationHelper();
helper.itemCount(["a", "b", "c", "d", "e", "f"], 4);


function PaginationHelper(collection, itemsPerPage){
this.collection=collection;
this.itemsPerPage=itemsPerPage;
}
PaginationHelper.prototype.itemCount = function() {
var self=this;
   return Math.floor(self.collection.length/self.itemsPerPage)
}
var helper = new PaginationHelper(['a','b','c','d','e','f'], 4);

helper.itemCount(); 
【热门文章】
【热门文章】