var windw = this;
$.fn.followTo = function ( pos ) {
var $this = this,$window = $(windw);
$window.scroll(function(e){
if ($window.scrollTop() > pos) {
//if condition
} else {
//else condition
}
});
};在上面的代码中,我不能理解关于使用'this‘和'$(this)’的问题。
通过像这样修改代码,让我们看看我试图理解的内容:
//var windw = this;
$.fn.followTo = function ( pos ) {
// var $this = this,$window = $(windw); // as far as I understand $window becomes $(this)
$(this).scroll(function(e){
if ($(this).scrollTop() > pos) {
//if condition
} else {
//else condition
}
});
};我也尝试了这么多:
//var windw = this;
$.fn.followTo = function ( pos ) {
// var $this = this,
// $window = $(windw);
this.scroll(function(e){
if (this.scrollTop() > pos) { // also tried $(this) here
//if condition
} else {
//else condition
}
});
};糟了!这两个代码都不能工作!
有没有人能有更好的方法来澄清我关于第一个放置的代码是如何工作的概念?
发布于 2014-01-13 13:26:57
在JavaScript中,“this”通常指的是“拥有”方法的对象,但这取决于函数的调用方式。
如果没有当前对象,‘this’指的是全局对象。在web浏览器中,这就是“窗口”--顶层对象,表示文档、位置、历史记录和其他一些有用的属性和方法。
当调用一个对象构造函数或它的任何方法时,‘this’指的是对象的实例-很像任何基于类的语言:
在你的代码中:
var windw = this; // there’s no current object, ‘this’ refers to the global object. ie, window.
$.fn.followTo = function ( pos ) {
// now this referes to the scope instance of $.fn.followTo which is not window
var $this = this,$window = $(windw);
$window.scroll(function(e){
// inside this closure this referes to the instace of this closure function which is not window
if ($window.scrollTop() > pos) {
//if condition
} else {
//else condition
}
});
};https://stackoverflow.com/questions/21084150
复制相似问题