node.js에 모듈 ( https://github.com/fluxxu/evalidator ) 의 확장 인 생성자가 있습니다. 이 확장 생성자는 프로토 타입에 두 가지 추가 메서드를 정의하고 ** 메서드 B 는 'this'키워드를 통해 메서드 A를 호출합니다 **. 이 생성자는 다른 객체의 속성을 초기화하는 데 사용되며이 속성에서 메서드 B를 호출하면 'main object'에 메서드 A가없는 것과 같은 오류가 발생합니다.
TypeError: Object function (){ superEvalidatorVar.method_B(); }
has no method 'method_B' at Object.<anonymous>
다음은 코드입니다.
var EValidator = require('evalidator');
/**
* EValidator extension object
* @constructor
*/
function SuperEValidator(){
// EValidator Inheritance
EValidator.apply(this, arguments);
}
SuperEValidator.prototype = Object.create(EValidator.prototype);
SuperEValidator.prototype.constructor = SuperEValidator;
SuperEValidator.prototype.method_A = function(){
console.log('method_A called');
};
SuperEValidator.prototype.method_B = function(){
this.method_A();
};
var superEvalidatorVar = new SuperEValidator();
var mainObject = {
callingSuperEValidator: function(){
superEvalidatorVar.method_B();
}
};
/*** Calling methods from MainObject ***/
mainObject.callingSuperEValidator.method_B(); // Throws Error!
** 확장 생성자의 method_B에있는 'this'키워드는 mainObject로 확인됩니다. 이유는 무엇입니까?
하지만 뭔가 나쁜 일이 있는지 궁금합니다 SuperEValidator에서이 동작을 이해하지 못합니다
편집하다:
이 모든 것의 진짜 목적은 Mongoose Schema의 'validate'메소드를 다시 작성하는 것입니다.
PostSchema.methods.validate = function(cb){
// 'this' will have the value of the object (model) from which the function will be called
evPost.validate_super(this, cb);
};
문제로 인해 아닌 this
, this
정확히 EV 준수합니다.
문제는 EV와 처음으로 만드는 것입니다 ev.__proto__==={}
후 재 할당 SuperEValidator.prototype
에서 연결을 해제하는 ev.__proto__
과 SuperEvalidator.prototype
.
여기서 SuperEValidator에 대한 함수 선언은 호이 스팅이지만 프로토 타입 정의에는 적용되지 않습니다. 문제를 해결하려면 mainObject를 맨 아래로 이동하기 만하면됩니다.
var mainObject = {
propertyObject: new PropertyObject(),
ev: new SuperEValidator() // at the moment, ev.__proto__ === {}
};
...
// SuperEValidator.prototype has been assigned to another reference while ev.__proto__ is still {}
SuperEValidator.prototype = Object.create(EValidator.prototype);
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다