2012-06-09 4 views
2

그래서 JS에서 간단한 Price 클래스를 만들고 싶다고합시다. 그것은 기본적으로 숫자입니다. 그래서 저는 제가 Number로부터 상속받을 것이라고 생각했습니다. 다음은 몇 가지 코드입니다.자바 스크립트 번호 상속성

Number.prototype.toMoney = function (precision, decimals, thousands) { 
    // Formats number... 
} 

function Price(val) { 
    Number.call(val); // Based on MozillaDN 
} 

Price.sufix = ' EUR'; // To print with every Price 

// Price.prototype = Number.prototype; 
Price.prototype = new Number(); // any difference? 

Price.prototype.toString = function() { 
    return this.toMoney() + Price.sufix; // Of course it does not work. 
} 

var price = new Price(100.50); 
alert(price.toString()); // Gives: undefined EUR 
alert(price); // This fail. I thought it should work as it works with Numbers. 

아마도 뭔가 잘못된 것이 있습니다. 그러나 나는 무엇을 발견 할 수 없습니다.

Price.prototype - new Number(); // any difference? 

그렇지 마이너스 기호에 서명 =을 사용할 필요가 있도록 가격의 프로토 타입이 될 수있는 새로운 번호를 할당됩니다

+0

fyi, 이는 'sufix'가 아니라 sufix입니다. 'Number.call()'도 약간 이상해 보입니다. 여러분이 그런 생성자 함수를 호출 할 수 있다고 생각하지 않습니다. – ThiefMaster

+0

이것은 "Number.prototype.valueOf가 일반적이지 않기"때문에 멋지게 작동하지 않습니다. 'Price' 인스턴스에 접근 할 수는 있지만 기본 숫자 값을 얻을 수는 없습니다. – pimvdb

+0

@pimvdb 나는 이것으로 이미 고투하고 있었다, 그러나 나는 그것이 거친 가능하다고 생각했다. 이것은 상속을 무시하고 ex에 대한 "value"라는 Price 클래스 내부의 속성을 만들어야한다는 것을 의미합니까? –

답변

0

당신은 내 생각이 라인에 오타가 있습니다.

읽어야

Price.prototype = new Number(); // any difference? 

가 여전히 작동하지 않습니다 가졌어요. Number에서 상속을 시도하는 이유를 이해할 수 없습니다.

이 작동 :

당신의 생성자가 수행되지
function Price(val) { 
    this.val = val;     
} 
Price.suffix = ' EUR'; // To print with every Price 

Price.prototype = { 
    toString: function() { 
     return this.toMoney() + Price.suffix; 
    }, 
    toMoney: function(precision, decimals, thousands){ 
     //fancy code here to format the number 
     return "formatted number " + this.val; 
    } 
}; 

var price = new Price(100.50); 
alert(price.toString()); // returns: formatted number 100.50 EUR 
alert(price); 
+0

이것은 단지 오타의 예입니다. 죄송합니다. –

0

당신은 무슨 생각을 : 생성자로 불리는

function Price(val) { 
    Number.call(val); // Based on MozillaDN 
} 

가 위가 일반 객체 (함수의 this 객체)을 반환합니다, val의 값에 관계없이 기본 값 +0 인 Number.call(val)에 의해 반환 된 값이 아닙니다. 따라서 반환하려고해도 생성자 은 항상이 반환하기 때문에 개체를 반환하기 때문에 생성자가 을 반환하므로 여전히 생성자가 반환합니다.

Number is called as a function 인 경우 유형 변환을 수행합니다. 아무런 값도 전달되지 않으므로 (val 값은 값이 제공되는 개체로 전달됨)이 식은 +0을 반환합니다.

어쨌든 요점은 무엇입니까? 값이 val 인 Number 객체를 만들려고합니까? Price.prototype 사용자 지정 toStringvalueOf 적절한 값을 반환하는 것이 좋습니다. Number.prototype과 같은 명명 된 메소드를 모방하는 것이 좋습니다.

> // Price.prototype = Number.prototype; 
> Price.prototype = new Number(); 
> // any difference? 

예, 두 번째는 가격 인스턴스에 대한 [[Prototype]] 체인에 추가 Number 객체를 추가합니다. 즉, Number.prototype에 영향을주지 않고 Price.prototype에 속성과 메서드를 추가 할 수 있습니다. 나는 거의 같은 질문에 대한 답을 찾고 때

function Price(value, symbol) { 
    this.value = value; 
    this.symbol = symbol; 
} 

Price.prototype = { 
    toString: function() { 
    return '' + this.symbol + this.valueOf(); 
    }, 

    valueOf: function() { 
    return this.value.toFixed(2); 
    } 
} 

var x = new Price(10.50, '$'); 

alert(x + '\n' + (1*x)); // $10.50 10.5 
2

,이 페이지를 발견 :

는 여기에 샘플 구현입니다. 이것이 최종 결론을 내리는 데 도움이됨에 따라, 나는 그것을 당신과 나누는 것을 좋아했습니다. Number에서 자신의 객체를 상속하는 것은 실제로 가능합니다.

function Price(val) { 
    Number.call(this, val); 
} 

이것은 일반적으로 부모 개체의 생성자를 호출하지만, 생성자가 val 자체를 반환하기 때문에이 경우는, 작동하지 않는 방법이다. 그리고 val을 읽으려고하면 "Number.prototype.valueOf가 일반이 아닙니다"오류가 수신됩니다.

alert(price.toString()); // Gives: undefined EUR 
alert(price); // This fail. I thought it should work as it works with Numbers. 
alert(price.valueOf()); // This fails too!() 

대신 Price (가격) 클래스에 val이라는 속성을 만들어야합니다.

function Price(val) { 
    this.val = val; 
} 

Price.sufix = ' EUR'; // To print with every Price 

// Price.prototype = Number.prototype; 
Price.prototype = new Number(); // any difference? 

JavaScript에서 상속 개체 인 Object.create() 메서드를 수행하는 방법이 있습니다. 그리고 생성자 객체가 이제 마지막으로 ..., 부모의 생성자에

Price.prototype = Object.create(Number.prototype); 
Price.prototype.constructor = Price; 

를 가리키는 때문에, 당신은 값을 읽기 위해 valueOf() 방법을 덮어 쓸 수 있습니다 : 그러나

Price.prototype.valueOf = function(){ 
    return this.val; 
    } 

var price = new Price(100.50); 
alert(price); //should work now 

을, 한쪽의 효과가있다 : Number 객체의 메서드가 필요하면 다음과 같이 호출해야합니다.

alert(price.valueOf().toFixed(2)); 
관련 문제