簡體   English   中英

從Number.prototype上的方法返回數字的值?

[英]Return number's value from method on Number.prototype?

在深入探討問題之前,我已經完全意識到要修改內置的原型。 這段代碼是用打字稿寫的。

好的,當我嘗試從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 從水龍頭返回時,我已經在調用this.valueOf() 誰都知道這是怎么回事。

剛剛嘗試了以下方法:

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

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

它運行得很好。

在此處輸入圖片說明

我想到了。 我缺少要求定義的Number.prototype.tap並已定義Object.prototype.tap的要求,因此導致了此問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM