封装了个JS对象没报错也无法运行
function lb_func(img_locate,num,direction,array){
//img_locate是<img>的id,num是图片的起始号,direction是表示轮播向左或右,array是装图片路径的数组
this.img_locate = img_locate;
this.num = num;
this.direction = direction;
this.array = array;
this.prototype = {
constructor : lb_func,
move: function(){
console.log("test");
//如果点右边
if( this.direction == "right" ){
this.num++;
if (this.num == array.length){
this.num = 0;
}
findEle(this.img_locate).setAttribute("src",this.array[this.num]);
}
//findEle()是document.getElementById()
//如果点左边
if( this.direction == "left" ){
this.num--;
if (this.num < 0 ){
this.num = array.length-1;
}
findEle(this.img_locate).setAttribute("src",this.array[this.num]);
}
}
}
}
findEle("lb1-right").onclick = new lb_func("lb1-1",a,"right",pics).move;
肉肉的娇妹妹
9 years, 11 months ago
Answers
2个问题
1. prototype属于构造函数的属性,不是实例的属性,构造函数内的this将来是属于实例的,所以不能使用this.prototype。你应该用
arguments.callee.prototype
或
lb_func.prototype
代替。
2.
onclick
的执行环境是
HtmlElement
实例,而
move
方法的执行环境是
lb_func
实例,所以你的最后一行的执行环境有问题。你应该改为
javascript
findEle("lb1-right").onclick = function () { //该函数的执行环境是find('lb1-right') new lb_func("lb1-1",a,"right",pics).move(); }
博丽魔理沙
answered 9 years, 11 months ago
prototype不能放到函数里面去写
function lb_func(img_locate, num, direction, array) {
//img_locate是<img>的id,num是图片的起始号,direction是表示轮播向左或右,array是装图片路径的数组
this.img_locate = img_locate;
this.num = num;
this.direction = direction;
this.array = array;
}
lb_func.prototype.move = function () {
console.log("test");
//如果点右边
if (this.direction == "right") {
this.num++;
if (this.num == array.length) {
this.num = 0;
}
findEle(this.img_locate).setAttribute("src", this.array[this.num]);
}
//findEle()是document.getElementById()
//如果点左边
if (this.direction == "left") {
this.num--;
if (this.num < 0) {
this.num = array.length - 1;
}
findEle(this.img_locate).setAttribute("src", this.array[this.num]);
}
}
轻飘飘的爱恋
answered 9 years, 11 months ago