1

我是一个新手程序员。我想以 OO 方式创建我的脚本。但是我想不出如何保护我的财产并且仍然能够访问它。问题是我无法this.XXX在函数中访问我的属性

this.handleStartEvent=function(event)

Firebug 中的错误信息:

“类型错误: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的属性startPointinitScale。有人可以指导我吗?

4

2 回答 2

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();
}
于 2012-08-08T11:17:24.613 回答
0

this.parent.getAttribute(...);如果 imgContainer 是父级,那么如果它是子级,则可以使用this.parent.getChildAt( index ).getAttribute(...);

将 index 替换为您要选择的元素的编号(索引)。如果它的第一个孩子喜欢<div><div class="wannaselectthat"></div></div>将索引设置为零。

于 2012-08-08T11:13:59.327 回答