Javascript - 如何在事件函数中访问对象属性?

时间:2012-08-08 11:07:53

标签: javascript html events web

我是一名新手程序员。我想以OO方式创建我的脚本。但是,我想不出如何保护我的属性,仍然能够访问它。问题是我无法访问函数

中的this.XXX属性
this.handleStartEvent=function(event)

Firebug中的错误消息:

  

“TypeError:this.imgContainer未定义”

整个脚本如下:

var imageViewer=function(imageWrapper)
{
    var hasTouch = 'ontouchstart' in window,
    resizeEvent = 'onorientationchange' in window ? 'orientationchange' : 'resize',
    startEvent = hasTouch ? 'touchstart' : 'mousedown',
    moveEvent = hasTouch ? 'touchmove' : 'mousemove',
    endEvent = hasTouch ? 'touchend' : 'mouseup',
    cancelEvent = hasTouch ? 'touchcancel' : 'mouseup';

    this.imgContainer=imageWrapper;
    this.image=imageWrapper.getElementsByTagName("img")[0];
    this.initScale=1;
    this.scaleLevel=this.initScale;
    this.startPoint={x:0,y:0}

    //alert(this.image)
    this.initEvents=function()
    {
        window.addEventListener(resizeEvent, this.resizeImageViewer, false);
        this.imgContainer.addEventListener(startEvent, this.handleStartEvent, false);
        this.imgContainer.addEventListener(moveEvent, this.handleMoveEvent, false);
        this.imgContainer.addEventListener(endEvent, this.handleEndEvent, false);
    }

    this.resizeImageViewer=function(event)
    {
        /*not finish*/
    }

    this.handleStartEvent=function(event)
    {
        /**********problem goes here*************/
        this.startPoint.x = event.offsetX || (event.pageX - this.imgContainer.offsetLeft); 
        this.startPoint.y = event.offsetY || (event.pageY - this.imgContainer.offsetTop);
    }

    this.handleMoveEvent=function(event)
    {
        /*not finish*/
    }

    this.handleEndEvent=function()
    {
        /*not finish*/
    }

    this.initEvents();
}

var imageViewerObj = new imageViewer(document.getElementById("imageWrapper"));

我知道this将是imgContainer,而不是imageViewer,但我不知道如何获取imageViewer的{​​{1}}属性}和startPoint。有人可以指导我一点吗?

2 个答案:

答案 0 :(得分:1)

如果您想继续引用this,只需将其保存在其他变量中:

var imageViewer = function(imageWrapper)
{
    var self = this; // use "self" instead of "this" later

    ...

    self.startPoint={x:0,y:0}

    self.initEvents=function()
    {
        window.addEventListener(resizeEvent, self.resizeImageViewer, false);
        self.imgContainer.addEventListener(startEvent, self.handleStartEvent, false);
        self.imgContainer.addEventListener(moveEvent, self.handleMoveEvent, false);
        self.imgContainer.addEventListener(endEvent, self.handleEndEvent, false);
    }

    ...

    self.initEvents();
}

答案 1 :(得分:0)

如果imgContainer是父级,则可以使用this.parent.getAttribute(...);如果是小孩this.parent.getChildAt( index ).getAttribute(...);

将index替换为您要选择的元素的数量(索引)。如果像<div><div class="wannaselectthat"></div></div>这样的第一个孩子将索引设置为零。