Home  >  Article  >  Web Front-end  >  Simple example of array inheritance in JavaScript_Basics

Simple example of array inheritance in JavaScript_Basics

WBOY
WBOYOriginal
2016-05-16 15:48:131183browse

Tree-structured data is often used when writing some libraries, and some tree-structured data have very high requirements for obtaining the path from root to leaf. For example, the entire routing table of a site is such a tree, and its "path" is actually the path part of the URL. So I have used crazy array inheritance several times to implement it, and I will share it with you below.
In JavaScript, arrays are also a type of Object and can also be inherited. Any two objects themselves can have an inheritance relationship, and arrays are no exception. So we let any node of a tree be an array, and it only maintains the value of the element with the largest subscript. The values ​​of other elements are inherited from ancestor nodes through prototypal inheritance. In this way, we can access the path from the root node on the leaf node just like operating a normal array. Here is a simple implementation:
Run

<script>
// 定义节点类
var TNode = function(value) {
 this.push(value);
};
TNode.prototype = [];
TNode.prototype.constructor = TNode;
TNode.prototype.createChild = function(value) {
 var node = Object.create(this);
 TNode.call(node, value);
 return node;
};

// 使用节点造出一棵简单的树
var root = new TNode('root');
var a = root.createChild('a');
var b = a.createChild('b');

// 将叶节点视为数组,直接得到路径
document.write(b.join('/')); <!-- root/a/b
</script>

This usage is considered a relatively dark magic, and it may be difficult to understand if you don’t understand the principle of prototypal inheritance. So if it is just an implementation of a library, it may be written like this (I have used it many times, and it turns out that there is no pitfall), but if it is used directly in business code, it may be complained to death. Although this usage does not violate the core idea of ​​​​the JavaScript language.
One feature of this usage is that when the value of the ancestor node is updated, it will automatically be synchronized to all child nodes. Although there is also a performance overhead when accessing the prototype chain, it is much faster than traversing the tree yourself at the code level. Of course, if there is no such demand and you just want to implement a simple number, it is better to use the traditional method. After all, this is too language-dependent, and it may be difficult to migrate to other programming languages ​​in the future.

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