向原型添加一个可以访问 "this" 的函数

Add a function to the prototype with access to "this"

一方面,我可以为一个对象分配一个新函数 Object.defineProperty(...).

然后我尝试将一个函数直接分配给NodeList Prototype。但不知何故它不能正常工作。我做错了什么?

Object.defineProperty(
  NodeList.prototype,
  'lastElement', { 
    get: function() {
      return this[this.length - 1].textContent;
    }
  }
);

NodeList.prototype.firstElement = () => {
   return this[0].textContent;
}

const h = document.querySelectorAll('span');
console.log('#last:', h.lastElement);
console.log('#first:', h.firstElement);
<div>
  <span>1</span>
  <span>2</span>
</div>

箭头函数 () => {...} 不仅仅是行为相同的不同语法,它们实际上以不同方式处理 this 关键字。

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions#arrow_functions_used_as_methods

如果您改用传统的函数语法,this 将按您的预期运行。

此外,您已将 firstElement 定义为常规函数,而不是 getter 函数,因此您需要这样调用它

console.log('#first:', h.firstElement());

Object.defineProperty(
  NodeList.prototype,
  'lastElement', { 
    get: function() {
      return this[this.length - 1].textContent;
    }
  }
);

NodeList.prototype.firstElement = function() {
   return this[0].textContent;
}

const h = document.querySelectorAll('span');
console.log('#last:', h.lastElement);
console.log('#first:', h.firstElement());
<div>
  <span>1</span>
  <span>2</span>
</div>