2012-11-26 4 views
1

나는 Node.JSExpressJS을 사용하고 있습니다. 다음 코드는 내 자신의 메시지로 Errors 객체를 확장하는 데 사용되며 충분히 잘 작동하지만, __proto__은 비표준임을 이해합니다.__proto__없이 다시 작성하는 방법

__proto__없이 다음 코드를 어떻게 다시 작성합니까?

var AccessDenied = exports.AccessDenied = function(message) { 
    this.name = 'AccessDenied'; 
    this.message = message; 
    Error.call(this, message); 
    Error.captureStackTrace(this, arguments.callee); 
}; 
AccessDenied.prototype.__proto__ = Error.prototype; 

답변

1
var AccessDenied = exports.AccessDenied = function (message) { /*...*/ }; 
var F = function () { }; 
F.prototype = Error.prototype; 
AccessDenied.prototype = new F(); 
2

사용 Object.create() 새로운 프로토 타입 객체를 만들고, 다시 비 열거 construtor 속성을 추가 할 수 있습니다.

AccessDenied.prototype = Object.create(Error.prototype, { 
    constructor: { 
     value: AccessDenied, 
     writeable: true, 
     configurable: true, 
     enumerable: false 
    } 
}); 

아니면 constructor 신경 쓰지 않는 경우 재산 :

AccessDenied.prototype = Object.create(Error.prototype); 
2
"use strict"; 

/** 
* Module dependencies. 
*/ 
var sys = require("sys"); 

var CustomException = function() { 
    Error.call(this, arguments);  
}; 
sys.inherits(CustomException, Error); 

exports = module.exports = CustomException; 
+1

왜'exports = module.exports = CustomException'을 설정했는지 궁금합니다. 이것은 무엇을 하는가? 나는 당신이 파일에서'exports' 또는'module.exports'를 사용했는데 둘 중 하나를 사용하지 않았다고 생각했습니다. –

+0

@ShaneStillwell'exports'는'module.exports'를 가리키고 있습니다. 기본적으로이 키는 빈 개체이므로 새 키를 둘 중 하나에 할당하면 작동합니다 (예 :'exports.thing = 42'). 그러나,'exports = 42'를하면 모듈에 국한된'exports' 변수를 덮어 쓰지 만'module.exports'는 여전히 빈 객체를 가리 킵니다. 둘 다 사용하는 것은 불필요한 것처럼 보일 수 있지만, 다른 방법으로도 작동합니다 :'module.exports'를 덮어 쓰면'exports'는 여전히 그 빈 객체를 가리 킵니다. 따라서 모듈의 다른 곳에서 문제가 발생하지 않도록하려면 두 모듈 모두에 할당하여 덮어 씁니다. – PPvG

관련 문제