采用以下代码:
function animateTo(parent) {
this.parent = $('#' + parent);
console.log(this.parent)
this.animator = function () {
this.parent.animate({
scrollTop: 5
}, 5);
}
}
test = new animateTo('data');
test.animator;
第一个 console.log
显示控制台中的完整对象,但是当我尝试运行 this.parent.animate
时,出现错误:
Uncaught TypeError: Object [object global] has no method 'animate' animator.js:60
(anonymous function
谁能解释一下这是为什么吗?我尝试过 this.parent.selector
并且得到了正确的结果,但是如果我尝试调用 animate 方法,就会收到该错误。
最佳答案
你应该这样做:
function animateTo(parent){
this.parent = $('#' + parent);
var that = this;
this.animator = function(){
that.parent.animate({scrollTop:5},5);
}
}
或
function animateTo(parent){
return {
parent: $('#' + parent),
animator: function(){
this.parent.animate({scrollTop:5},5);
}
}
}
如果您不喜欢这些选项中的任何一个,您始终可以使用bind
,但除非您不关心旧浏览器,否则您必须使用填充程序。
例如(在现代浏览器中):
function animateTo(parent){
this.parent = $('#' + parent);
this.animator = (function(){
this.parent.animate({scrollTop:5},5);
}).bind(this)
}
或使用下划线或lodash:
function animateTo(parent){
this.parent = $('#' + parent);
this.animator = _.bind(function(){
this.parent.animate({scrollTop:5},5);
}, this)
}
顺便说一下,习惯上将构造函数大写,因为它们被视为类型(就像基于类的面向对象语言中的类)。
关于javascript - 分配给该变量后,JQuery 方法将不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18346088/