javascript - 命名空间对象原型(prototype)

标签 javascript

我想使用一些额外的方法来增强对象,例如向数组添加 first()second() 方法,但使用命名空间,以便它以 [1, 2].item.second() 方式调用,而不是 [1, 2].second()。我得到如下代码,但我得到未定义

Array.prototype.item = {
    first: function () {
        return this[0];
    },
    second: function () {
        return this[1];
    }
};

[1, 2].item.second()
// undefined
// I don't want to use [1, 2].second()

最佳答案

first()second() 函数中的 this 引用了 item 属性数组,而不是数组本身,这就是为什么你会得到未定义

最简单的方法是将 item 转换为方法来捕获正确的上下文,如下所示:

Array.prototype.item = function() {
  var _this = this;

  return {
    first: function() {
      return _this[0];
    },
    second: function() {
      return _this[1];
    }
  };
};

然后:

[1, 2].item().first(); // 1
[1, 2].item().second(); // 2

根据您的更新,如果您坚持使用原始属性语法,您可以尝试以下操作:

Object.defineProperty(Array.prototype, 'item', {
  get: function() {
    var _this = this;

    return {
      first: function() {
        return _this[0];
      },
      second: function() {
        return _this[1];
      }
    };
  }
});

然后:

[1, 2].item.first(); // 1
[1, 2].item.second(); // 2

参见MDN

关于javascript - 命名空间对象原型(prototype),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44995753/

相关文章:

javascript - React with redux - 使用 redux-form 进行 react 评级

javascript - 将数据库状态与运行时添加的数据合并

javascript - 通过 Google Apps 脚本检索修订文本

javascript - 使用某些正则表达式模式时,为什么我的函数不能正确替换

Javascript 找不到元素 ID

Safari 中的 JavaScript 错误,只是有时

javascript - 使用 css :hover declaration 选择元素

javascript - firebase 数据库调用的数组记录了正确的数据,但长度显示为 0

javascript - D3js 选择所有文本

javascript - Electron webview 新窗口事件返回 `about:blank` 作为 Url