Home >Web Front-end >JS Tutorial >Comprehensive analysis of JavaScript object-oriented layered thinking

Comprehensive analysis of JavaScript object-oriented layered thinking

高洛峰
高洛峰Original
2016-12-05 16:17:04995browse

js itself is not an object-oriented language. In fact, object-oriented thinking is rarely used in our actual development. I used to think that it was encapsulated into objects when it was to be reused. However, as the projects we are doing now are in the later testing stage, we found that object-oriented The role of it is not only reuse, you may say that object-oriented also has the concept of inheritance and polymorphism, but the concept of polymorphism does not exist in JavaScript, and inheritance requires the web page to download js first before running, resulting in js Inheritance cannot be as flexible as the background and js does not have overloading and rewriting is inconvenient (and the meaning of rewriting in js is not very significant), so object-oriented is rarely used in js, and objects may be seen in some plug-ins. Anyone who writes JS will have the same feeling when writing a plug-in. Generally, the plug-in function is first written out through the face-to-face process, and then refactored into an object method. However, in actual project development, time progress and development costs are required. There is rarely such a loose time for you to use process-oriented implementation of functions before refactoring. In actual development, we basically use the process-oriented process to write it and submit it directly.

A problem with this writing method is that when you After writing this page, some time later suddenly the functional requirements or page layout of this page need to be adjusted. When you look at the code of this page, it is difficult to quickly sort out the logical steps of the entire page's code. I believe that many people who write front-end Everyone feels the same! For example: I wrote the magnifying glass plug-in a few years ago. Now when I released it, I found that the plug-in I wrote had no effect when Google Chrome rendered it for the first time. The code is as follows:

/// <reference path="../jquery11.js" />
(function ($) {
$.fn.extend({
jqoom: function (potions) {
var settings = {
width: 350,
height: 350,
position: "right"
}
if (potions) {
$.extend(settings, potions);
}
var ImgUrl = $("img", this).attr("src");
var ImgMinWidth = $("img", this).width();
var ImgMinHeigth = $("img", this).height();
var ImgWidth = 0;
var ImgHeight = 0;
var de = true;
$(this).hover(function (e) {
}, function () {
$("#jqoomz").remove();
$(document).unbind("mousemove");
$("#jqoomy").remove();
de = true;
});
$("img", this).hover(function (e) {
var pagex = e.x || e.pageX;
var pagey = e.y || e.pageY;
var pagex1 = 0;
var pagey1 = 0;
var leftcha = 0;
var topcha = 0;
_this = $(this).parents("div");
if ($("#jqoomz").length == 0) {
_this.after("<div id=&#39;jqoomz&#39;></div>");
var obj = new Image();
obj.src = ImgUrl;
obj.onload = function () {
if (de && obj.height > 0) {
de = false;
ImgWidth = obj.width;
ImgHeight = obj.height;
finder.call(_this.find("img")[0]);
}
};
$("#jqoomz").width(settings.width).height(settings.height).offset({
left: $(_this).outerWidth() + $(_this).offset().left,
top: $(_this)[0].offsetTop
}).append($("<img  alt="Comprehensive analysis of JavaScript object-oriented layered thinking" ></img>").attr("src", ImgUrl));
if (de && obj.height > 0) {
de = false;
ImgWidth = obj.width;
ImgHeight = obj.height;
finder.call(this);
}
}
function mover(event) {
var pagex2 = event.x || event.pageX;
var pagey2 = event.y || event.pageY;
if (parseInt(pagex2 + leftcha) <= parseInt($(_this).width() + $(_this).offset().left) && pagex2 >= leftcha + $(_this).offset().left) {
$(this).offset({left: pagex2 - leftcha});
} else {
if (parseInt(pagex2 + leftcha) > parseInt($(_this).width() + $(_this).offset().left) && pagex2)
$(this).offset({left: $(_this).width() + $(_this).offset().left - leftcha * 2});
else
$(this).offset({left: $(_this).offset().left});
}
if (parseInt(pagey2 + topcha) <= parseInt($(_this).height() + $(_this).offset().top) && pagey2 >= topcha + $(_this).offset().top) {
$(this).offset({top: (pagey2 - topcha)});
//document.getElementById("move").style.top = (pagey2 - (this.pagey - this.divtop)).toString() + "px";
} else {
if (parseInt(pagey2 + topcha) > parseInt($(_this).height() + $(_this).offset().top))
$(this).offset({top: ($(_this).height() + $(_this).offset().top - topcha * 2)});
//document.getElementById("move").style.top = (this.height - this.divHeight).toString() + "px";
else
$(this).offset({top: $(_this).offset().top});
//document.getElementById("move").style.top = "0px"
}
var bilx = ($(this).offset().left - $(_this).offset().left) / (ImgMinWidth / ImgWidth);
var bily = ($(this).offset().top - $(_this).offset().top) / (ImgMinHeigth / ImgHeight);
$("#jqoomz img").css({"margin-left": -bilx, "margin-top": -bily});
}
function finder() {
if (parseFloat($(this).offset().top + $(this).height() - (ImgMinHeigth / ImgHeight * ImgMinHeigth)) >=
parseFloat(pagey - ImgMinHeigth / ImgHeight * ImgMinHeigth / 2) && parseFloat(pagey - ImgMinHeigth / ImgHeight * ImgMinHeigth / 2) >=
parseFloat($(this).offset().top)) {
pagey1 = (pagey - ImgMinHeigth / ImgHeight * ImgMinHeigth / 2);
} else {
if ((pagey - ImgMinHeigth / ImgHeight * ImgMinHeigth / 2) < $(this).offset().top) {
pagey1 = $(this).offset().top;
} else {
pagey1 = ($(this).offset().top + $(this).height() - (ImgMinHeigth / ImgHeight * ImgMinHeigth));
}
}
if (($(this).offset().left + $(this).width() - ImgMinWidth / ImgWidth * ImgMinWidth) >=
(pagex - ImgMinWidth / ImgWidth * ImgMinWidth / 2) && (pagex - ImgMinWidth / ImgWidth * ImgMinWidth / 2) >=
$(this).offset().left) {
pagex1 = (pagex - ImgMinWidth / ImgWidth * ImgMinWidth / 2);
} else {
if ((pagex - ImgMinWidth / ImgWidth * ImgMinWidth / 2) < $(this).offset().left) {
pagex1 = $(this).offset().left;
} else {
pagex1 = ($(this).offset().left + $(this).width() - ImgMinWidth / ImgWidth * ImgMinWidth);
}
}
leftcha = ImgMinWidth / ImgWidth * ImgMinWidth / 2;
topcha = ImgMinHeigth / ImgHeight * ImgMinHeigth / 2;
if ($("#jqoomy").length == 0) {
$(this).after("<div id=&#39;jqoomy&#39;></div>")
.siblings("#jqoomy")
.addClass("jqoomy").show()
.width((ImgMinWidth / ImgWidth * ImgMinWidth))
.height((ImgMinHeigth / ImgHeight * ImgMinHeigth)).offset({
top: pagey1,
left: pagex1
});
}
$(document).on("mousemove", $.proxy(mover, $("#jqoomy")));
}
}, function () {
});
}
});
})(jQuery);

html:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
<script src="jquery11.js"></script>
<script src="OppJqoom.js"></script>
<style type="text/css">
.jqoom
{
width: 350px;
height: 350px;
border: solid 1px #DFDFDF;
z-index: 10;
}
.jqoom img
{
cursor: pointer;
z-index: 10;
max-height: 350px;
max-width: 350px;
}
.jqoomy
{
background-color: white;
position: relative;
z-index: 999;
opacity: 0.5;
cursor: pointer;
border: solid 1px #DFDFDF;
}
#jqoomz
{
border: solid 1px #DFDFDF;
position: absolute;
overflow: hidden;
}
.lef
{
border: 1px solid #DFDFDF;
display: block;
height: 72px;
line-height: 72px;
text-align: center;
text-decoration: none;
width: 10px;
background-color:#EBEBEB;
float:left;
}
.lef:hover
{
color:red;
}
.jqooz
{
float:left;
width:352px;
margin-top:20px;
}
.jqooz ul
{
float: left;
margin: 0;
padding: 0;
width:328px;
height:72px;
}
.jqooz ul li
{
display: inline;
list-style: none outside none;
margin: 0 10px;
}
.jqooz ul li img
{
border: 1px solid #DFDFDF;
max-height: 72px;
max-width: 120px;
}
.jqooz ul li img:hover
{
border: 1px solid #ff6600;
}
</style>
<script type="text/javascript">
$(function () {
$(".jqoom").jqoom();
});
</script>
</head>
<body>
<div class="jqoom">
<img  src="b3.jpg" / alt="Comprehensive analysis of JavaScript object-oriented layered thinking" >
</div>
<div class="jqooz">
<a href="javascript:void(0)" class="lef"><</a>
<ul>
<li><a>
<img  src="b3.jpg" / alt="Comprehensive analysis of JavaScript object-oriented layered thinking" ></a></li>
</ul>
<a href="javascript:void(0)" class="lef">></a>
</div>
</body>
</html>

Effect:

Comprehensive analysis of JavaScript object-oriented layered thinking

Now I want to modify why this plug-in has no effect when Google Chrome is loaded for the first time, then I have to follow the code again to sort out the entire functional steps in the magnifying glass, this The function of the magnifying glass is not very complicated. In actual projects, various function callback nesting, data retrieval, data processing, display, and dynamic effects of the page are all intertwined in onload or ready. It will take you several hours or even a whole day to do it. Sort out the code logic of the page you want to modify, and it may not be possible to sort it out comprehensively, so often when front-end colleagues add comments to previously written pages after a while, they will say that I can’t even understand the code I wrote.

One of the characteristics of JavaScript itself is event listening function callback, which is its advantage. One of the reasons why nodejs authors choose js is the advantage brought by JavaScript event listening function callback, but function callback also brings a disadvantage that it often appears. Data cannot be returned. A typical example is ajax. jQuery's traditional ajax callback success method is successful. When you want to use the output of this ajax as the input of another ajax, you have to nest ajax. Once there are too many nests, The readability and complexity of this code have increased a lot! Later maintenance has also naturally increased the difficulty. After Promise came out, jQuery and angular also added Promise. Why does JavaScript spend so much time sorting out the logic in later maintenance?

We are taking a look at how the background Java or C# language is used. Typical Javaweb is almost all spring MVC framework. C# is undoubtedly .net MVC for web. The common feature of them is that the C layer provides ajax calls to the front-end page. The methods are split one by one according to the required data, and relative to the M layer, MVC is actually layered in two dimensions. This is my personal opinion. One dimension is a single small function divided into view and control. , model, another dimension is that the entire page is divided into multiple small functions. So if you find that it is easy to sort out the logic when modifying the back-end code, then can the front-end javascript be layered according to the whole idea?

This plug-in It does not involve dynamic number retrieval, so the standards for layering are also different. Here I divide it into two layers. The first layer is a series of algorithms for pictures after the mouse moves, and the second layer is a series of DOM divided into event bindings. The operation, the code is as follows:

/**
* Created by on 2016/11/2.
*/
(function ($) {
//构造函数逻辑主线路
var OppJqoom = function (_this, potions) {
this._this = _this;
this.ImgUrl = $("img", this._this).attr("src");
this.ImgMinWidth = $("img", this._this).width();
this.ImgMinHeigth = $("img", this._this).height();
this.ImgWidth ,this.ImgHeight ,this.leftcha,this.topcha;
var settings = {
width: 350,
height: 350,
position: "right"
}
$.extend(this,settings);
if (potions) {
$.extend(this, potions);
}
this.domOperation.Jqoomhover.call(this);
this.domOperation.imghover.call(this);
};
OppJqoom.prototype = {
// 第一层 算法层
basicOperation: {
/* 获取遮罩层的top和left*/
finder: function (that) {
var pagey1, pagex1;
if (parseFloat($(this).offset().top + $(this).height() - (that.ImgMinHeigth / that.ImgHeight * that.ImgMinHeigth)) >=
parseFloat(this.pagey - that.ImgMinHeigth / that.ImgHeight * that.ImgMinHeigth / 2) && parseFloat(this.pagey - that.ImgMinHeigth / that.ImgHeight * that.ImgMinHeigth / 2) >=
parseFloat($(this).offset().top)) {
pagey1 = (this.pagey - that.ImgMinHeigth / that.ImgHeight * that.ImgMinHeigth / 2);
} else {
if ((this.pagey - that.ImgMinHeigth / that.ImgHeight * that.ImgMinHeigth / 2) < $(this).offset().top) {
pagey1 = $(this).offset().top;
} else {
pagey1 = ($(this).offset().top + $(this).height() - (that.ImgMinHeigth / that.ImgHeight * that.ImgMinHeigth));
}
}
if (($(this).offset().left + $(this).width() - that.ImgMinWidth / that.ImgWidth * that.ImgMinWidth) >=
(this.pagex - that.ImgMinWidth / that.ImgWidth * that.ImgMinWidth / 2) && (this.pagex - that.ImgMinWidth / that.ImgWidth * that.ImgMinWidth / 2) >=
$(this).offset().left) {
pagex1 = (this.pagex - that.ImgMinWidth / that.ImgWidth * that.ImgMinWidth / 2);
} else {
if ((this.pagex - that.ImgMinWidth / that.ImgWidth * that.ImgMinWidth / 2) < $(this).offset().left) {
pagex1 = $(this).offset().left;
} else {
pagex1 = ($(this).offset().left + $(this).width() - that.ImgMinWidth / that.ImgWidth * that.ImgMinWidth);
}
}
that.leftcha = that.ImgMinWidth / that.ImgWidth * that.ImgMinWidth / 2;
that.topcha = that.ImgMinHeigth / that.ImgHeight * that.ImgMinHeigth / 2;
that.domOperation.docMousemove.call(that);
return {top: pagey1, left: pagex1};
},
// 放大镜的图片的top和left
mover: function (that) {
if (parseInt(that.pagex2 + that.leftcha) <= parseInt(that._this.width() + that._this.offset().left) && that.pagex2 >= that.leftcha + that._this.offset().left) {
$(this).offset({left: that.pagex2 - that.leftcha});
} else {
if (parseInt(that.pagex2 + that.leftcha) > parseInt(that._this.width() + that._this.offset().left) && that.pagex2)
$(this).offset({left: that._this.width() + that._this.offset().left - that.leftcha * 2});
else
$(this).offset({left: that._this.offset().left});
}
if (parseInt(that.pagey2 + that.topcha) <= parseInt(that._this.height() + that._this.offset().top) && that.pagey2 >= that.topcha + that._this.offset().top) {
$(this).offset({top: (that.pagey2 - that.topcha)});
//document.getElementById("move").style.top = (pagey2 - (this.pagey - this.divtop)).toString() + "px";
} else {
if (parseInt(that.pagey2 + that.topcha) > parseInt(that._this.height() + that._this.offset().top))
$(this).offset({top: (that._this.height() + that._this.offset().top - that.topcha * 2)});
//document.getElementById("move").style.top = (this.height - this.divHeight).toString() + "px";
else
$(this).offset({top: that._this.offset().top});
//document.getElementById("move").style.top = "0px"
}
var bilx = ($(this).offset().left - that._this.offset().left) / (that.ImgMinWidth / that.ImgWidth);
var bily = ($(this).offset().top - that._this.offset().top) / (that.ImgMinHeigth / that.ImgHeight);
return{left:bilx,top:bily};
}
},
// 第二层 事件绑定层
domOperation: {
// 鼠标移动到图片的一系列dom的操作
imghover: function () {
var that = this;
$("img", this._this).hover(function (e) {
this.pagex = e.x || e.pageX;
this.pagey = e.y || e.pageY;
var offset;
var obj = new Image();
obj.src = that.ImgUrl;
obj.onload = function () {
if (obj.height > 0) {
that.ImgWidth = obj.width;
that.ImgHeight = obj.height;
if ($("#jqoomz").length == 0) {
that._this.after("<div id=&#39;jqoomz&#39;></div>");
}
offset = that.basicOperation.finder.call(that._this.find("img")[0],that);
}
};
if ($("#jqoomz").length == 0) {
that.ImgWidth = obj.width;
that.ImgHeight = obj.height;
that._this.after("<div id=&#39;jqoomz&#39;></div>");
}
offset = that.basicOperation.finder.call(this,that);
if ($("#jqoomy").length == 0) {
$(this).after("<div id=&#39;jqoomy&#39;></div>")
.siblings("#jqoomy")
.addClass("jqoomy")
.show()
.width((that.ImgMinWidth / that.ImgWidth * that.ImgMinWidth))
.height((that.ImgMinHeigth / that.ImgHeight * that.ImgMinHeigth))
.offset({
top: offset.top,
left: offset.left
});
}
$("#jqoomz").width(that.width).height(that.height).offset({
left: that._this.outerWidth() + that._this.offset().left,
top: that._this[0].offsetTop
}).append($("<img  alt="Comprehensive analysis of JavaScript object-oriented layered thinking" ></img>").attr("src", that.ImgUrl));
},function () {});
},
//鼠标在图片上滑动的一系列dom操作
docMousemove: function () {
var that=this;
$(document).on("mousemove", function (event) {
that.pagex2 = event.x || event.pageX;
that.pagey2 = event.y || event.pageY;
var offset=that.basicOperation.mover.call($("#jqoomy"),that);
$("#jqoomz img").css({"margin-left": -offset.left, "margin-top": -offset.top});
});
},
//鼠标移除图片的一系列dom操作
Jqoomhover:function () {
this._this.hover(function (e) {
}, function () {
console.log(111);
$("#jqoomz").remove();
$(document).unbind("mousemove");
$("#jqoomy").remove();
});
}
}
};
$.fn.extend({
jqoom: function (potions) {
return new OppJqoom(this, potions);
}
})
})(jQuery);

Then add a simple comment to feel that the logical steps of the page are very clear. Of course, one of the more troublesome things about this writing method is the usage of this. The nested object in the object calls the method this Point to your own object.

In actual development, we can be divided into data reading layer, data processing layer, and DOM dynamic effect layer. If the business is more complex, it can also be divided into data display layers.


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn