为什么我不能在 JavaScript 中使用 "x = $("p").offset; Top = x().top"?

Why can't I use "x = $("p").offset; Top = x().top" in JavaScript?

我正在使用 jQuery 并且需要获取一个元素的位置。

我先这样写代码:

 x=$("p").offset;
 Top = x().top; // bug here

我发现浏览器找不到顶部,因为这里 x() 为空。

所以我改写成这样:

x=$("p").offset;
y=$("p").offset();
Top = y.top;

好的,现在可以了。

但是为什么??? 我认为 y.top 应该与 x().top 相同,因为 x() 是 $("p").offset().

这是一个例子

function P() {
  this.pos = {top: 1, left: 1}
}
P.prototype.offset = function() {
  return this.pos
}

const p = new P()
console.info('p.offset().top:', p.offset().top)

const fn = function() {
  return this.pos // won't work when called normally, ie fn()
}

console.info('fn.call(p).top:', fn.call(p).top) // works

const x = p.offset // x is equivalent to fn
console.info('x.call(p).top:', x.call(p).top)
console.info('x().top:', x().top) // doesn't work

最后一个错误,因为方法 offset(现在分配给 x)没有 this 上下文供 return this.pos 工作。

这就是为什么 this 在该调用中未定义的原因。

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call