2013-11-02 4 views
1

thisundefined으로 다음과 같은 경고를받는 이유는 무엇입니까?프로토 타입에 액세스 할 수 없음

http://jsfiddle.net/7kwXd/6/

var testObj = {}; 

testObj.aMethod = function() { 
    this.testVar = "thing" 
    alert(this.anObject.dimension1); 
    alert(this.anObject.dimension2); 
}; 

testObj.aMethod.prototype.anObject = { 
    dimension1 : this.testVar, 
    dimension2 : "thing2" 
}; 

var testing = new testObj.aMethod(); 

답변

2

당신은 어떤 개체 컨텍스트가없는 객체 ({dimension1: this.testVar, dimension2: "thing2"})을 만들 수 있습니다. 그 당시의 this은 무엇입니까? 그런 다음 testObj.aMethod.prototype.anObject에 할당합니다.

var testObj = {}; 

testObj.aMethod = function() { 
    this.testVar = "thing" 
    alert(this.anObject.dimension1); 
    alert(this.anObject.dimension2); 
}; 

testObj.aMethod.prototype.getAnObject = function() { 
    return { 
     dimension1 : this.testVar, 
     dimension2 : "thing2" 
    }; 
}; 

var testing = new testObj.aMethod(); 

을 그리고 testing.getAnObject().dimension1에 해당 개체에 액세스 :

당신은 당신이 원하는 것을 달성하기 위해 다음과 같은 코드를 사용할 수 있습니다.

관련 문제