2015-01-23 3 views
0

DOM 요소의 속성 그룹을 어떻게 자동화 할 수 있는지 궁금합니다. 나는 다음과 같이 작동하지만 코드가 무슨 뜻인지 이해를 참조하지 않습니다 알고기본 속성 (jQuery 없음)으로 구성된 JS에서 개체 생성자 만들기

function interface(bg, color, size, margin, content) { 
    this.style.backgroundColor=bg; //native html properties 
    this.style.color= last; 
    this.style.fontSize = size; 
    this.style.marginLeft = margin; 
    this.innerHTML=content; 
} 

var Green = new interface("green", "white", "20px", "20", "the green one"); 
var Blu = new interface("blue", "white", "48px", "0", "the blue one"); 

document.getElementById("demo").interface = Green; 

그래야 속성의 그룹들을 다시 하나 하나를 가리 키도록하지 않고 적용됩니다. 완전히 벗어 났습니까?

+0

속성을 반복하여 복사하십시오. 다양한 라이브러리가 이러한 기능을 구현하므로 직접 작성하거나 표준 ['Object.assign'] (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/)을 사용하는 것이 쉽습니다. 개체/할당). 'style'을 적절히 다루기 위해서는 "deep extension"기능이 필요할 수도 있습니다. –

+0

@FelixKling이 시점에서'Object.assign' "standard"를 호출하는 것이 정확한지 확신 할 수 없습니다. – JLRishe

+0

@JLRishe : ECMAScript 6의 일부입니다. 얼마나 더 표준이 될 수 있습니까? –

답변

1

왜 이렇게하고 싶은지는 모르겠지만 가능성은 있습니다.

function Interface(bg, color, size, margin, content) { 
 
    this.bg = bg; 
 
    this.color = color; 
 
    this.size = size; 
 
    this.margin = margin; 
 
    this.content = content; 
 
} 
 

 
Interface.prototype.implement = function (element) { 
 
    element.style.backgroundColor = this.bg; 
 
    element.style.color = this.color; 
 
    element.style.fontSize = this.size; 
 
    element.style.marginLeft = this.margin; 
 
    element.innerHTML = this.content; 
 
}; 
 

 
var green = new Interface("green", "white", "20px", "20px", "the green one"), 
 
    blu = new Interface("blue", "white", "48px", "0", "the blue one"); 
 

 
green.implement(document.getElementById("demo"));
<div id="demo">Demo</div>

첨가

Object.assign (ECMA6)의 가능한 해결책으로서 @FelixKling 언급 되었으나 깊고 연장 될 필요가 있으며 단지 얕은는 연장 제공 . 다음은 기본 딥 연장 (ECMA5)의 예입니다.

/*global document */ 
 
(function() { 
 
    'use strict'; 
 

 
    var assigner = function (target) { 
 
      if (target && typeof target === 'object') { 
 
       Array.prototype.slice.call(arguments, 1).forEach(function (source) { 
 
        if (source && typeof source === 'object') { 
 
         Object.keys(source).forEach(function (key) { 
 
          var copy = source[key], 
 
           src, 
 
           clone, 
 
           type; 
 

 
          if (target !== copy) { 
 
           type = typeof copy; 
 
           if (type === 'object') { 
 
            src = target[key]; 
 
            if (src && typeof src === 'object') { 
 
             clone = src; 
 
            } else { 
 
             clone = {}; 
 
            } 
 

 
            target[key] = assigner(clone, copy); 
 
           } else if (type !== 'undefined') { 
 
            target[key] = copy; 
 
           } 
 
          } 
 
         }); 
 
        } 
 
       }); 
 
      } 
 

 
      return target; 
 
     }, 
 

 
     green = { 
 
      style: { 
 
       backgroundColor: 'green', 
 
       color: 'white', 
 
       fontSize: '20px', 
 
       marginLeft: '20' 
 
      }, 
 
      innerHTML: 'the green one' 
 
     }; 
 

 
    assigner(document.getElementById("demo"), green); 
 
}());
<div id="demo">Demo</div>

는 어쩌면 누군가는 일반적인 깊은 방식으로 Object.assign을 사용하는 방법이있다?

+0

"구현"의 철자가 잘못되었습니다. :) 그러나 아마도 "적용"이 더 좋은 이름이 될 것입니다. – JLRishe

+0

예. :) 나는'적용 '의 사용을 피하려고 노력했다. – Xotic750

+0

예, 유효 지점입니다. :) – JLRishe

1

Xotic은 좋은 답을 제공하고있다, 그러나 당신이 할 수있는 또 다른 흥미로운 방법은 함수가 작업을 수행하는 다른 기능을 생성하는 것입니다 :

function makeDomUpdater(bg, color, size, margin, content) { 
 
    return function(element){ 
 
    element.style.backgroundColor = bg; 
 
    element.style.color = color; 
 
    element.style.fontSize = size; 
 
    element.style.marginLeft = margin; 
 
    element.innerHTML = content; 
 
    }; 
 
} 
 

 
var green = makeDomUpdater("green", "white", "20px", "20", "the green one"), 
 
    blu = makeDomUpdater("blue", "white", "48px", "0", "the blue one"); 
 

 
green(document.getElementById("demo"));
<div id="demo">Demo</div>

이하지 않습니다 객체 생성자를 사용하지만, 다시는 모든 것이 필요하지는 않습니다. :)

+0

'인터페이스'는 [(미래의) 예약어입니다.] (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#Future_reserved_keywords) – Xotic750

+0

@ Xotic750 나는 그것을 몰랐다. 고맙습니다! – JLRishe

0

먼저 JavaScript에서 클래스, 프로토 타입, 생성자 등을 이해하기 위해 (이것은 당신이 가고있는 것으로 보입니다), 무료 책 (페이퍼 백으로 구입할 수도 있음)을 추천 할 수 있습니다 : http://eloquentjavascript.net/. 당신은 이것을 파헤치는 시간을 가져야 만합니다. 개념은 당신이 (언어 적으로) 오는 것보다 다소 다릅니다.

방금 ​​예제로 사용한 것을 알고 있지만 모든 스타일 속성의 경우 HTML 클래스와 해당 CSS 정의를 사용해야합니다. 요소에 적용하려면 클래스를 지정해야합니다. 그런 식으로, DOM 요소는 "CSS 인터페이스 green"을 구현합니다. 나는 별도로 콘텐츠를 처리 할 것입니다. 당신의 유사 자바 스크립트 코드를 작업에 대한

.green { 
    background-color: green; 
    color: white; 
    font-size: 20px; 
    margin-left: 20px; // margin-left needs a unit 
} 

.blue { 
    background-color: blue; 
    color: white; 
    font-size: 48px; 
    margin-left: 0; // at least if it isn't zero 
} 

, JLRishe'sXotic750's 답변을 참조하십시오.