我编写了一个带有原型的函数构造函数,该原型创建了 svg 图片并将其插入到网页中。我有两个问题:
1 可以把创建实例过程中用到的构造函数内部的部分代码移到原型对象中吗?据我所知,这些原型方法通常用于已创建的实例,例如var a = [2,3,4]; a.reverse()
2 在函数构造函数内部以这种方式操作 DOM 对象可以吗?DOM 对象不是 js 原生对象,它们是 js-engine 之外的宿主对象。它们类似于 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>