从Number.prototype上的方法返回数字的值?

时间:2016-05-25 02:58:41

标签: javascript typescript

在深入了解问题的细节之前,我已经完全了解修改内置的原型。此代码用typescript编写。

好的,所以当我尝试从Number.prototype上的方法返回一个数字的值时,我遇到了一个问题。

以下是Number.prototype的定义:

Object.defineProperty(Number.prototype, 'tap', {
  value: function numberTap (fn: (t: number) => void): number {
    fn.call(null, this.valueOf());
    return this.valueOf();
  }
});

我正在运行的测试:

describe('Number.prototype.tap((value:number) => void): number', () => {
  it('is defined', function () {
    expect(Number.prototype.tap).to.be.a('function');
  });

  it('returns the same value as its entry point in the method chain', () => {
    expect((1).tap(n => 5)).to.equal(1);
  });
});

它不等于1而是[Number 1]。如果我致电[Number 1].valueOf(),则会返回1。从tap中返回时我已经在呼叫this.valueOf()。任何人都知道这里发生了什么。

2 个答案:

答案 0 :(得分:0)

试过以下内容:

Object.defineProperty(Number.prototype, 'tap', {
  value: function numberTap(fn) {
    fn.call(null, this.valueOf());
    return this.valueOf();
  }
});

typeof (1).tap(function(){})

它运行得很好。

enter image description here

答案 1 :(得分:0)

我明白了。我错过了一个定义了Number.prototype.tap的require,并且已经定义了Object.prototype.tap,因此导致了这个问题。