首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >jQuery如何在原型中调用方法?

jQuery如何在原型中调用方法?
EN

Stack Overflow用户
提问于 2015-03-25 18:42:09
回答 1查看 320关注 0票数 2

jQuery:

代码语言:javascript
复制
    function Morphing( button, container, content) {
    this.button = button;
    this.container = container;
    this.content = content;
    this.overlay = $('div.overlay');
}

Morphing.prototype.startMorph = function() {
    this.button.on('click', function() {
        $(this).fadeOut(200);
        Morphing.containerMove();
        // Work on from here!
        // setTimeout(Morphing.containerMove, 200);
    });
};

Morphing.prototype.containerMove = function() {
    console.log(this);
    this.overlay.fadeIn();
    this.container.addClass('active');

    this.container.animate(Morphing.endPosition, 400, function() {
            this.content.fadeIn();
            this.span.fadeIn();
            Morphing.close();
    });
};

我试图在单击按钮时运行containerMove函数,但是,我收到了以下错误:

代码语言:javascript
复制
[Error] TypeError: undefined is not a function (evaluating 'Morphing.containerMove()')
    (anonymous function) (newScript.js, line 11)
    dispatch (jquery.min.js, line 3)
    i (jquery.min.js, line 3)

这是唯一的错误。我想是因为我调用的方法不对吧?谢谢。

附带说明:在原型中编写方法是否像我所做的那样是一个很好的实践?

额外代码:

忘了说,这是在我的index.html:

代码语言:javascript
复制
<script>
$(document).ready(function() {

    var morph = new Morphing( $('button.morphButton'), $('div.morphContainer'), $('h1.content, p.content') );

    morph.startMorph();

});

</script>
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-03-25 18:46:18

最简单的方法是将原始this存储在闭包中。

代码语言:javascript
复制
Morphing.prototype.startMorph = function() {
    var me = this;
    this.button.on('click', function() {
        $(this).fadeOut(200);
        me.containerMove();
        // Now for the set timeout, you'll want to make sure it's
        // called with the corect `this`, You can use Function.bind
        // See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind
        setTimeout(me.containerMove.bind(me), 200);
    });
};

在您的事件处理程序中,this指向元素本身,正如您从调用$(this).fadeOut(200);这一事实中了解到的那样,但是您需要访问处理程序之外的this

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/29263925

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档