1
안녕하세요 저는이 모듈 패턴 변형을 사용하고 있으며 부모 객체에 액세스하는 가장 좋은 방법을 찾고 있습니다. 부모 개체가 무엇인지 알 수있는 방법이 없다는 것을 알고 있으므로 생성자에 컨텍스트를 포함하고 싶습니다. 이게 효과가있을 거라 생각했는데 어떤 생각이 들지?javascript 모듈 패턴 변형을 사용하는 동안 부모 객체에 액세스
$(document).ready(function(){
var main = new Main();
});
function Main() {
var one = 'hello';
init();
function init() {
var data = new Data(this);
var two = data.load();
console.log(one+' '+two);
data.output();
}
}
function Data(context) {
// public vars/methods
var pub = {
'load' : function() {
return ('world');
},
'output' : function() {
var one = context.one // <-- what should this be?
var two = this.load();
console.log (one+' '+two);
}
}
return pub;
}
출력은 다음과 같습니다 당신이 new
연산자와 생성자 함수를 호출 할 때, 당신은 기본적으로
function Main(){
var this = //magic new object
//provided by the runtime
//your code comes here
return this;
//because your Data function returns a value,
// you never get to this line. Perhaps you should use
// a regular non-constructor data() function instead?
}
같은 일을하고있다
hello world
undefined world
대답 해 주셔서 감사합니다. 필자의 예제에는 복잡성이 더해질 필요가 없다는 것에 동의하며 패턴을 보여주기 위해 가능한 한 간단하게 만들었습니다. 다시 한 번 감사드립니다! – pixelscript