2014-09-23 1 views
1

그래서 나는 JavaScript에서는 숫자 기능을 상속하는 방법이 있습니까?

Number.prototype.square = function() { return this * this } 
[Function] 
4..square() 
16 

내가 번호 프로토 타입을 수정할 필요가 없습니다 있도록 번호 기능에서 상속 할 수있는 방법이 있나요 ... 난 할 수있어? 함수 또는 객체를 사용하면 다음과 같이 상속받을 수 있습니다.

var NewObject = new Object() 
var NewFunction = new Function() 

비슷한 번호가있는 것이 있습니까?

+0

문제는 명확하지 않다 : -/ –

+0

나는 명확성을 위해 질문을 편집했다. – amorphid

답변

3

예, 쉽게 Number.prototype에서 상속받을 수 있습니다. 트릭은 그들에게 .valueOf 방법을 제공하여 숫자로 개체를 전환하는 것입니다 :

function NumLib(n) { 
    if (!(this instanceof NumLib)) return new NumLib(n); 
    this.valueOf = function() { 
     return n; 
    } 
} 
NumLib.prototype = Object.create(Number.prototype); 
NumLib.prototype.square = function() { return this * this } 

캐스팅 수학 연산이 개체에 적용 할 때마다, 또한 this answer 참조 발생합니다. 네이티브 Number 메서드는 실제로 파생 된 객체에서 호출되는 것을 좋아하지 않습니다.

1

을 사용하면 Object.defineProperty을 사용하면 개체를 조금 더 제어 할 수 있습니다. 자신과

Object.defineProperty(Number.prototype,'square',{value:function(){ 
return this*this 
},writable:false,enumerable:false}); 
//(5).square(); 

이 같은 해방 ...

Object.defineProperty(NumLib.prototype,'square',{value:function(){ 
return this.whatever*this.whatever 
},writable:false,enumerable:false}); 
관련 문제