JavaScript 23 가지 디자인 모델 의 2 원형 모델
40458 단어 디자인 모드
개념: 이미 만 든 인 스 턴 스 를 원형 으로 하고 이 인 스 턴 스 대상 을 복사 하여 원형 과 같 거나 비슷 한 새로운 대상 을 만 듭 니 다.
특징:
구조 와 실현
원형 모드 에 서 는 인 스 턴 스 대상 을 원형 으로 제공 하고 이 원형 을 복제 하 는 방법 을 제공 해 야 합 니 다.이곳 의 복 제 는 또 얕 은 복사 와 깊 은 복사 로 나 뉜 다.자 바스 크 립 트 에 서 는 주로 Object. create 를 통 해 대상 clone 을 실현 합 니 다.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<title>React App</title>
</head>
<body>
<script>
function Person(name) {
this.name = name;
this.clone = function (param) {
return Object.create(this,{name:{value:param||name}});
}
}
var obj1 = new Person("jack");
var obj2 = obj1.clone();
var obj3 = obj1.clone("rose");
console.log(obj1);
console.log(obj2);
console.log(obj3);
console.log("obj1==obj2?"+(obj1==obj2));
</script>
</body>
</html>
응용 장면
응용 실례
가상 DOM 을 실현 하여 눈 송 이 를 대량으로 제조 하 다.가상 DOM 생 성 과정 을 간단히 말씀 드 리 겠 습 니 다.
new
방법 으로 트 리 구 조 를 만 드 는 요소 대상 을 재 귀적 으로 말한다.createElement
구조 함수.new
방법 으로 연결 합 니 다.다음 사례 에서 원형 모델 을 사용 하 는 곳 이 두 번 째 단계 다.구조 함수 에
mountComponent
방법 을 추가 하 였 다.그래서 눈꽃 을 대량으로 만 들 때 가상 DOM 대상 을 대량으로 만 들 지 않 습 니 다.직접 clone
방법 을 통 해 이 루어 지고 서로 다른 스타일 로 들 어가 전체 화면 크기 가 다 르 고 위치 가 다른 눈꽃 효 과 를 실현 한다. // DOM
function ReactDOMComponent(element) {
// element
this._currentElement = element;
this._rootNodeID = null;
//
this.clone = function (style) {
//1. 。
var str = JSON.stringify(this);
var newObj = JSON.parse(str);
//2. this, prototype 。
newObj.__proto__ = this;
if(style){
newObj._currentElement.props.style = style;
}
return newObj;
}
}
//
var componentInstance = instantiateReactComponent(element) // vDom Component
//
var html = componentInstance.mountComponent(0);
//
for(var i=0;i<100;i++){
var el= componentInstance.clone(
"left:"+parseInt(Math.random() * window.innerWidth)+"px;"+
"top:"+parseInt(Math.random() * (window.innerHeight-0))+"px;"+
"font-size:"+parseInt(Math.random() * (50))+"px"
);
var markup1 = el.mountComponent(0);
html+=markup1;
}
root.innerHTML = html;
전체 코드:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<title>React App</title>
</head>
<style>
.snow{
color:#fff;
position: absolute;
opacity: 0.9;
}
</style>
<body style="background: black">
<div id="root"></div>
<script>
// DOM
function createElement(type, config, children) {
var props = {};
var propName;
config = config || {};
var key = config.key || null;
for (propName in config) {
if (config.hasOwnProperty(propName) && propName !== "key") {
props[propName] = config[propName];
}
}
var childrenLength = arguments.length - 2;
if (childrenLength === 1) {
props.children = Array.isArray(children) ? children : [children];
} else if (childrenLength > 1) {
var childArray = [];
for (var i = 0; i < childrenLength; i++) {
childArray[i] = arguments[i + 2];
}
props.children = childArray;
}
return new ReactElement(type, key, props);
}
function ReactElement(type, key, props) {
this.type = type;
this.key = key;
this.props = props;
}
//
function ReactDOMTextComponent(text) {
//
this._currentElement = "" + text;
}
//
ReactDOMTextComponent.prototype.mountComponent = function() {
return this._currentElement;
};
// DOM
function ReactDOMComponent(element) {
// element
this._currentElement = element;
this._rootNodeID = null;
//
this.clone = function (style) {
//1. 。
var str = JSON.stringify(this);
var newObj = JSON.parse(str);
//2. this, prototype 。
newObj.__proto__ = this;
if(style){
newObj._currentElement.props.style = style;
}
return newObj;
}
}
// DOM
ReactDOMComponent.prototype.mountComponent = function() {
var props = this._currentElement.props;
//
var tagOpen = " + this._currentElement.type;
var tagClose = "" + this._currentElement.type + ">";
//
for (var propKey in props) {
if (props[propKey] && propKey != "children" && !/^on[A-Za-z]/.test(propKey)) {
tagOpen += " " + propKey + "=" + props[propKey];
}
}
// dom
var content = "";
var children = props && props.children || [];
var childrenInstances = []; // component
children.forEach((child, key) => {
var childComponentInstance = instantiateReactComponent(child);
//
childComponentInstance._mountIndex = key;
childrenInstances.push(childComponentInstance);
//
var childMarkup = childComponentInstance.mountComponent();
//
content += " " + childMarkup;
});
// component
this._renderedChildren = childrenInstances;
// html
return tagOpen + ">" + content + tagClose;
};
//
function instantiateReactComponent(node) {
//
if (typeof node === "string" || typeof node === "number") {
return new ReactDOMTextComponent(node);
}
//
if (typeof node === "object" && typeof node.type === "string") {
// , component
return new ReactDOMComponent(node);
}
}
//
var element = createElement(
'div',
{class:'snow'},
'❆'
);
//
var componentInstance = instantiateReactComponent(element) // vDom Component
//
var html = componentInstance.mountComponent(0);
//
for(var i=0;i<100;i++){
var at = componentInstance.clone(
"left:"+parseInt(Math.random() * window.innerWidth)+"px;"+
"top:"+parseInt(Math.random() * (window.innerHeight-0))+"px;"+
"font-size:"+parseInt(Math.random() * (50))+"px"
);
var markup1 = at.mountComponent(0);
html+=markup1;
}
root.innerHTML = html;
</script>
</body>
</html>
총결산
상기 사례 에서 원형 모델 을 실현 하 는 두 가지 관건 적 인 절차.
new
을 통 해 계승 을 실현 한다 (원형 상의 속성 과 방법 을 사용 할 수 있다).이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
디자인 모델 의 공장 모델, 단일 모델자바 는 23 가지 디자인 모델 (프로 그래 밍 사상/프로 그래 밍 방식) 이 있 습 니 다. 공장 모드 하나의 공장 류 를 만들어 같은 인 터 페 이 스 를 실현 한 일부 종 류 를 인 스 턴 스 로 만 드 는 것...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.