JQuery方法获胜'分配给这个变量后不起作用

JQuery method won't work after assignment to this variable

本文关键字:变量 不起作用 分配 获胜 方法 JQuery      更新时间:2023-09-26

获取以下代码:

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();