在自定义函数构造函数中操作DOM

时间:2018-09-20 10:03:56

标签: javascript svg function-constructor

我用原型创建了一个函数构造函数,该原型正在创建svg图片并将其插入到网页中。我有两个问题:

1是否可以在创建实例的过程中使用正在构造器中的代码并将其移至原型对象。据我所知,这些原型方法通常用于已创建的实例,例如var a = [2,3,4]; a.reverse()

2在函数构造函数中以这种方式操作DOM对象是否很好? DOM对象不是js本机对象,它们是js引擎之外的宿主对象。它们类似于js对象,但由浏览器在其他地方创建

下面是代码:

function Sektor(selector, options) {
// Find a DOM object representing the HTML element with the supplied selector
// create a property called element
// This DOM object is assigned to the element property
  this.element = document.querySelector(selector);

// Some default values in case nothing is supplied
  const defaultOptions = {
    size: 100,
    circleColor: '#b3c9e0'
  };

// Merge options with default ones
  options = Object.assign(defaultOptions, options);
	
// Circle dimensions
  options.center = options.size / 2;
  options.radius = options.center;
  
// create a property called options
  this.options = options;

// Get SVG
  const svg = this.getCircle();

// SVG is injected into the DOM element with JavaScript
  this.element.innerHTML = svg;
}

// Assigning a method to the constructor's prototype
// This method generates SVG
Sektor.prototype.getCircle = function() {
  const options = this.options;
  return `
  <svg class='Sektor' viewBox='0 0 ${options.size} ${options.size}'> 
  <circle class='Sektor-circle' fill=${options.circleColor} cx='${options.center}' cy='${options.center}' r='${options.radius}' />
  </svg>
  `;
};


var sektor = new Sektor( '.example-one', { circleColor: '#7da385' } );
<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width">
	<title>Draw</title>
	<style>
body {
	margin: 0;
	padding: 0;
}

.examples {
	display: flex;
	justify-content: space-between;
	padding: 20px;
}

.example {
	margin: 0px auto;
}

.Sektor {
	width: 200px;
	height: 200px;
	background-color:#f2f2f2;
}
	</style>
</head>
<body>
	<div class='examples'>
		<div class='example'>
			<div class='example-one'></div>
		</div>
	</div>		
	<script src='sektor.js'></script>
</body>
</html>

0 个答案:

没有答案