javascript - 这个JS原型方法怎么写

查看:124
本文介绍了javascript - 这个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);

这篇关于javascript - 这个JS原型方法怎么写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆