2016-10-29 7 views
0

나는 codecademy.com의 코스를 따라 JavaScript bij를 배우려고 노력하고 있지만 'this'키워드를 이해하지 못하는 것 같습니다. 또한 사각형의 속성 너비와 높이를 변경해야합니다.Codecademy Javascript 'this'and solution

var rectangle = new Object(); 
    rectangle.height = 3; 
    rectangle.width = 4; 
    // here is our method to set the height 
    rectangle.setHeight = function (newHeight) { 
     this.height = newHeight; 
    }; 
    // help by finishing this method 
    rectangle.setWidth = 


    // here change the width to 8 and height to 6 using our new methods 

현재 내가 가지고 :

var rectangle = new Object(); 
    rectangle.height = 3; 
    rectangle.width = 4; 

    rectangle.setHeight = function (newHeight) { 
     this.height = newHeight; 
    }; 
    rectangle.setWidth = function (newWidth) { 
     this.width = newWidth; 
    }; 

    rectangle.setWidth = setWidth; 
    rectangle.setHeight = setHeight; 
    rectangle.setWidth(8); 
    rectangle.setHeight(6); 

내가 무슨 일을 했는가 이것은 시작이다? 또한 오류 메시지는 setWidth를 정의하지 않았다는 것을 알려줍니다 ...

'this'도 설명하십시오.

답변

2

이 부분은 정확 :

// since these two methods are going to be called as methods of `rectangle` object 
// `this` inside these functions will be set to reference `rectangle` object 
rectangle.setWidth(8); 
rectangle.setHeight(6); 

그러나, 스크립트에 도착하지 않습니다

rectangle.setHeight = function (newHeight) { 
    // `this` here is not set yet when declaring functions 
    // it will be set when the function will be executed 
    this.height = newHeight; 
}; 
rectangle.setWidth = function (newWidth) { 
    this.width = newWidth; 
}; 

그런 다음 할, 당신이 뭘하려는 건지 그냥이 작업을 수행해야 setWidthsetHeight 보낸

rectangle.setWidth = setWidth; 
rectangle.setHeight = setHeight; 

문제 발생이 부분 때문에 상기 코드가 재이다 기존 변수가 없으므로 Uncaught ReferenceError: setWidth is not defined(…) 오류가 발생합니다. 이 부분은 실제로 필요하지 않으므로 간단히 제거하면 정상적으로 작동합니다.

this에는 풍부한 자바 스크립트가 있습니다. MDN으로 시작하십시오.

+0

@MrNirusu ??? 이 대답에 설명 된대로 잘못된 코드 줄을 제거하십시오. – Pointy

+0

단순히 제거, 내 대답에 그것을 언급했다 –

+0

@MrNirusu, 그것은 작동 했습니까? 그렇다면 내 대답을 수락하는 것을 고려하십시오. –