繁体   English   中英

JavaScript对象中的“ this”与jQuery $(this)

[英]“this” in JavaScript objects vs. jQuery $(this)

我偶然发现了一个问题。 我有一个对象方法foo定义为:

var obj = {
    foo: function() {
        $('.personName').mouseover(function() {
            this.highlight($(this).attr('faceIndex'));
        });
    }
}

因此,应该发生的情况是,每当鼠标光标位于personName类型的HTML对象上时, personName使用HTML对象中的faceIndex值作为参数来调用obj.highlight方法。 但是我显然有冲突,这两者之间是:jQuery的的一个和JavaScript的一个(引用到obj从内obj )。

我能(应该)做什么? 我违反了一些良好的编程习惯吗?

解决此问题的典型模式是使用局部变量存储第一个this

var obj = {
    foo: function() {
        var _this = this;
        $('.personName').mouseover(function() {
            _this.highlight($(this).attr('faceIndex'));
        });
    }
}

使用TypeScript之类的语言或ES6编译器可以更轻松地使用此模式,而不必每次都手动编写_this

简短答案:

    $('.personName').mouseover(function(event) {
        obj.highlight($(event.target).attr('faceIndex'));
    });

更长的解释:

JavaScript并没有真正的概念this 至少不会像以前那样思考它。 哦,这里有一个很好的关键字,它在很多时候都可以满足您的期望,但是它并不能像您想象的那样起作用。

事实是,在javascipt中, this与任何其他参数没有什么不同。 让我演示给你看。

大多数人都知道,在javascript中,您可以调用类似doSomething(param1, param2)或类似doSomething.call(null, param1, param2)函数。 如果需要,可以使用.call编写所有函数调用

看到那null吗? 你在那里通过什么就是this被设置为。

doSomething.call(null, param1, param2);
doSomething.call(obj, param1, param2);
doSomething.call(window, param1, param2);
doSomething.call("foobar", param1, param2);

如果您不使用.call则运行时仅猜测您想要的值。

因此,考虑到这一点,请考虑this参数与任何其他参数之间的唯一区别是不要给this一个名字! 您的问题是您有两个函数作用域,而内部作用域具有一个名为this的变量, this变量隐藏了外部作用域的this

解决方案:不要使用this 实际上,大多数库(包括jquery)都不要强迫您使用this并且也将值作为常规参数传递

    $('.personName').mouseover(function(event) {
        obj.highlight($(event.target).attr('faceIndex'));
    });

歧义解决了!

尽可能避免在JavaScript中使用this 几乎没有必要。

this在JavaScript是一件非常困难的事情在回调中理解,因为它可能涉及到了任何实例。 那是因为回调是从不同的上下文中调用的。

漫长的故事: https : //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this

作为先前答案的替代方法:

我更喜欢处理它的一种方法是使用bind (在JQuery中也称为proxy )。 jQuery在这里实现了一个: jQuery.proxy

它的好处是让您在回调函数中选择谁是您的this

例如:

var obj = {
    foo: function() {
        $('.personName').mouseover($.proxy(function(event) {
          // this refers here to obj instance
          console.log(this);
          // event is a jQuery decorated that holds the reference of your element 
          console.log(event);
        }, this));
    }
};

它的真正好处是,它使您可以构建没有“丑陋”的嵌套回调匿名函数的组件:

var obj = {
    foo: function() {
        $('.personName').mouseover($.proxy(this.mouseOverCallback, this));
    },
    mouseOverCallback : function(event) {
       // this refers here to obj instance
       console.log(this);
       // event is a jQuery decorated that holds the reference of your element 
       console.log(event);
    }
};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM