2013-12-19 2 views
0

프로토 타입을 사용하여 H2 제목을 만들어서 필요에 따라 개별적으로 설정할 수 있습니다.프로토 타입 javascript를 사용하여 제목 스타일 설정

H2에 텍스트를 추가하려면 this.appendChild(document.createTextNode(''));을 사용하고 있습니다. 나는이 경우에 appendChild이기 전에 this 키워드라고 말하기 전에 부모 노드를 사용해야하지만 부모로 인식되고 있는지 또는 실제로 부모인지는 확실하지 않습니다. 또한 생성자 자체의 매개 변수를 통해 텍스트를 추가하는 방법에 관해서도 확실하지 않습니다. 변수 '글꼴'을 사용했지만 CSS 스타일을 추가하지 않는 방법을 잘 모르겠습니다.

프로토 타입을 사용하는 방법을 배우고 있습니다. 내가 놓친 다른 명백한 오류가 있다면 알려주십시오.

<div id='body'> 
<div id='inner'>div here</div> 
</div> 
<script> 
Heading.prototype.font; 
Heading.prototype.color; 
Heading.prototype.fontSize; 
Heading.prototype.headingTxt; 
Heading.prototype.setHeading = function() { 

    var inner = document.getElementById('inner'); 
    this.headingTxt = document.createElement('h2'); 
    this.headingTxt.font = this.appendChild(document.createTextNode('')); 
    this.headingTxt.style.color = this.color; 
    this.headingTxt.style.fontSize = this.fontSize; 
inner.appendChild(headingTxt); 
} 

function Heading(font, color, fontSize) { 

    this.font = font; 
    this.color = color; 
    this.fontSize = fontSize; 
} 

var title = new Heading('heading here', 'red', 20); 
title.setHeading(); 

</script> 

어떻게하면이 문제를 해결할 수 있습니까? 내가 옷을 벗었

+0

상위 노드는 무엇입니까? 'this '는 DOM 엘리먼트가 아닌'Heading'의 인스턴스, 즉'title'을 참조합니다. –

+0

분명히 'this'를 사용하는 것이 잘못되었습니다. 텍스트 노드가 자식이되도록 부모로 생성되는 'H2'요소를 참조하기를 원합니다. – moonshineOutlaw

답변

0

Heres는 작업 버전 : 당신이 정말로 인스턴스를 다시해야하는 경우

function Heading(font, color, fontSize) { 
    this.font = font; 
    this.color = color; 
    this.fontSize = fontSize; 
} 

Heading.prototype.setHeading = function() { 
    var inner = document.getElementById('header'); //make sure inner exists 
    this.headingTxt = document.createElement('h2'); //you could also scope this to be local with var if you want it to be private 
    inner.appendChild(this.headingTxt); 
} 

var title = new Heading('heading here', 'red'); 
title.setHeading(); 
0

사용 프로토 타입은 올바른 것입니다. 그러나 이상적으로 나중에 값을 변경할처럼, 나중에 그와 함께 할 더 많은 것 : 인스턴스를 다시 사용할 필요가없는 경우

(function (window, undefined) { 

    window.Heading = (function() { 

     var Heading = function (text, fontColor, fontSize, element) { 

      // Re-enforce instance 
      if (!(this instanceof Heading)) 
       return new Heading(text, fontColor, fontSize, element); 

      // Validate Element. element can be null 
      element = (element.nodeType) ? element : null; 

      // Get first H2 element in the page if not element is informed 
      if (element === null) { 

       var h2 = window.document.getElementsByTagName('H2'); 

       if (h2.length) 
        // Get first H2 element from the page 
        element = h2[0]; 

      } else if (element.nodeType !== 1) 

       // Validate if this is an Element 
       throw new Error('Only Element type is accepted.'); 

      this._element = element; 
      this._fontColor = fontColor; 
      this._fontSize = fontSize; 
      this._text = text; 
     }; 

     Heading.prototype.set = function() { 

      var propertyName = (this._element.textContent) ? 'textContent' : 'innerText'; 

      this._element[propertyName] = this._text; 
      this._element.style.fontSize = this._fontSize; 
      this._element.style.color = this._fontColor; 

      return this; 
     }; 

     Heading.prototype.values = function (text, fontColor, fontSize) { 

      this._fontColor = fontColor; 
      this._fontSize = fontSize; 
      this._text = text; 

      return this; 
     }; 

     return Heading; 

    })(); 

})(window); 

// Example 
var instance = Heading('First exmaple', 'red', '20px'); 

// Set 
instance.set(); 

// Re-use 
instance.values('Second example', 'blue').set(); 

것은, 간단한 함수가 적합 할 수 있습니다.

var Heading = function (text, fontColor, fontSize, element) { 

    // Validate Element. element can be null 
    element = (element.nodeType) ? element : null; 

    // Get first H2 element in the page if not element is informed 
    if (element === null) { 

     var h2 = window.document.getElementsByTagName('H2'); 

     if (h2.length) 
      // Get first H2 element from the page 
      element = h2[0]; 

    } else if (element.nodeType !== 1) 

     // Validate if this is an Element 
     throw new Error('Only Element type is accepted.'); 

    var propertyName = (element.textContent) ? 'textContent' : 'innerText'; 

    element[propertyName] = text; 
    element.style.fontSize = fontSize; 
    element.style.color = fontColor; 
};