JQuery方法获胜'分配给这个变量后不起作用
JQuery method won't work after assignment to this variable
获取以下代码:
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中的作用域。简短的版本是:每次打开新的function
时,都会创建一个新的作用域。您的代码粘贴显示了两个嵌套作用域,其中内部作用域中的this
与外部作用域的this
不匹配。
无论如何,解决方案很简单,因为您甚至不需要在场景中使用this
function animateTo(parent){
var $parent = $('#' + parent);
console.log($parent)
this.animator = function(){
$parent.animate({scrollTop: 5}, 5);
};
}
var test = animateTo('data');
test.animator;
不过,你似乎在试图做这样的事情。
以下是我将如何编写此代码的意见
var Animator = function(selector) {
this.parent = $(selector);
};
Animator.prototype.animate = function() {
this.parent.animate({scrollTop: 5}, 5);
};
使用情况看起来像这个
var test = new Animator("#data");
test.animate();
相关文章:
- javascript美元符号变量不起作用
- Url中的JavaScript变量不起作用
- 全局变量不起作用
- 彩色变量不起作用
- 变量不起作用(不知道为什么)javascript
- Angularjs 更新 setTimeout 中的范围变量不起作用
- 将 jQuery 函数分配给变量不起作用,但包装它不起作用
- 谷歌图表-重新格式化变量不起作用
- AngularJS-ng显示范围变量不起作用
- 在 JavaScript 中设置变量不起作用
- 如何将 html 输入值传递给 php?- 变量不起作用
- Javascript变量等于下面的另一个变量不起作用
- Javascript 初学者 - 全局变量不起作用
- JavaScript 中的全局变量不起作用
- d3 本地存储比较数组 .filter 咖啡脚本;数组变量不起作用
- JS中的PHP变量不起作用
- 作为“名称”的Javascript数组变量不起作用
- 鼠标上的补间变量不起作用
- Javascript onclick 变量不起作用
- 角度 JS 范围变量不起作用