2012-12-11 5 views
0

자바 스크립트에서 OOP 코딩의 초보자입니다.OOP에서 클래스의 높이 및 너비 설정 Javascript

클래스의 크기를 설정하려고합니다. 하지만 내 코드에서 오류가 발생했습니다. 내가 얻을 콘솔에서

var block1 = new Block(); 
block1.appendTo('body').setSize(100,100); 

:

(function($) { 

    Block = function() { 
     var self = this; 
     this.el = $('<div></div>'); 
    } 

    Block.prototype.appendTo = function(parent) { 
     this.el.appendTo(parent); 
    } 

    Block.prototype.setSize = function(width, height) { 
     var self = this; 
     this.width = width; 
     this.height = height; 
    } 

})(jQuery); 

이 내가 클래스를 호출하는 방법입니다 당신은 appendTo의 반환 값에 setSize 호출

Uncaught TypeError: Cannot call method 'setSize' of undefined 

답변

1

. 그러나 appendTo은 아무 것도 반환하지 않으므로 (undefined) setSize을 호출하면 오류가 발생합니다.

(function($) { 

    Block = function(width, height) { 
     this.el = $('<div></div>'); 
     if (width !== undefined && height !== undefined) { 
      this.width = width; 
      this.height = height; 
     } 
    } 

    Block.prototype.appendTo = function(parent) { 
     this.el.appendTo(parent); 
     return this; 
    } 

    Block.prototype.setSize = function(width, height) { 
     this.width = width; 
     this.height = height; 
    } 

})(jQuery); 
+0

이 anwser 주셔서 감사합니다,하지만 난 "에는 setSize"로 크기를 설정하려면 :

이에 대한 솔루션과 같이, 당신의 appendTo 기능에서 Block 개체를 반환하는 것입니다. 그래서 당신이 var block1 = new Block(); block1.appendTo ('body'). setSize (100,100); div의 크기는 100x100 px입니다. – user1386906

+0

당신은 - 내 것을 당신의 것으로 대체 할 수 있습니다. 나는 그 일찍 언급했지만 어쩌면 눈에 띄지는 않았다. 이 문제에 필요한 유일한 것은'width = -1; 높이 = -1; 섹션 – Swadq

+0

mabye iam 뭔가를 내려다 보지만 여전히 같은 오류가 있습니다. 여기에 바이올린 : http://jsfiddle.net/BqNfe/ – user1386906

관련 문제