jQuery的:
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函数,但我收到错误:
[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:
<script>
$(document).ready(function() {
var morph = new Morphing( $('button.morphButton'), $('div.morphContainer'), $('h1.content, p.content') );
morph.startMorph();
});
</script>
答案 0 :(得分:3)
最简单的方法是将原始this
存储在闭包
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
这一事实中理解