보세요. 내가이 클래스가,자바 스크립트 OOP에서 GLOBAL 개체를 상속받습니다.
function Exception(){}
Exception.prototype = {
messages: {},
add: function(k, v){
if(!Array.isArray(this.messages[k])) this.messages[k] = new Array
this.messages[k].push(v)
}
}
그리고 :
// @alias ActiveRecord.extend
...
extend: function extend(destination, source){
for (var property in source){
destination[property] = source[property];
}
return destination;
}
...
나는이 클래스를 가지고있다. 그리고 메소드 this에서 호출합니다. 에러는 새로운 Exception입니다.
function Validations(){
this.errors = new Exception
}
그리고이 모델을 만들고, 모델에 유효성 검사가 있습니다. 유효성 검사에 오류가 있습니다. 나는 새로운 인스턴스에게 모델을 생성하고이 인스턴스에 오류를 추가 할 때
ActiveSupport.extend(Model.prototype, Validations.prototype)
function Model(){};
하지만 ... 는 클래스 예외 는 전역 객체로 나타납니다. 보기 ...
a = new Model
a.errors.add('a', 1);
console.log(a.errors.messages) // return {a: [1]}
b = new Model
b.errors.add('a', 2);
console.log(b.errors.messages) // return {a: [1,2]}
어떻게 해결할 수 있습니까?
Exception 클래스의 메시지 배열을 GLOBAL로 만들지 않으려면 어떻게해야합니까?
errors 객체 내부에있는 메시지 객체를 변경하지 않으므로 console.log (a.errors.messages)가 어떻게 표시할지 모르겠습니다. 전체 코드를 보여 주시겠습니까? – Aravind
'Validations' 객체를 어떻게 구성합니까? – dfsq
Scimonster 대답은 올바른 것입니다. 메시지는 Exception.prototype에서 왔으며 Exception 인스턴스간에 공유됩니다. 한 인스턴스에서 프로토 타입 멤버를 변경하면 모든 인스턴스에서이 멤버가 변경됩니다. 어쩌면 다음과 같은 답변이 인스턴스 별, 프로토 타입 멤버 및 섀도 잉을 이해하는 데 도움이 될 것입니다. http://stackoverflow.com/a/16063711/1641941 – HMR