/*修改Node的原型链*/
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body>
<ul>
<li id="item1">选项1</li>
<li id="item2">选项2</li>
<li id="item3">选项3</li>
<li id="item4">选项4</li>
<li id="item5">选项5</li>
</ul>
</body>
</html>
------------------------------------------------------------
/*修改Node的原型链*/
Node.prototype.getSiblings = function(){
var allChildren = this.parentNode.children
var array = {
length:0
}
for(let i = 0 ;i<allChildren.length; i++){
if(allChildren[i] !== this){
array[array.length] = allChildren[i]
array.length += 1
}
}
return array
}
Node.prototype.addClass = function(classes){
for(let key in classes){
var value = classes[key]
var methodName = value ? 'add' : 'remove'
this.classList[methodName](key)
}
}
console.dir(item3)
console.log(item3)
console.log(item3.getSiblings())
console.log(item3.addClass({'a':true,'b':true,'c':true}))
console.log(item3.getSiblings.call(item3))
console.log(item3.addClass.call(item3,{'a':true,'b':true,'c':true}))
------------------------------------------------------------------------------
-----------------------Node2[无侵入]---------------------------------------
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body>
<ul>
<li id="item1">选项1</li>
<li id="item2">选项2</li>
<li id="item3">选项3</li>
<li id="item4">选项4</li>
<li id="item5">选项5</li>
</ul>
</body>
</html>
----------------------------------------------------------------------------
window.Node2 = function(node){
return{
getSiblings:function(){
var allChildren = node.parentNode.children
var array = {
length:0
}
for(let i = 0 ;i<allChildren.length; i++){
if(allChildren[i] !== node){
array[array.length] = allChildren[i]
array.length += 1
}
}
return array
},
addClass:function(classes){
for(let key in classes){
var value = classes[key]
var methodName = value ? 'add' : 'remove'
node.classList[methodName](key)
}
}
}
}
var node2 = Node2(item3)
console.log(Node2)
console.log(node2)
console.log(node2.getSiblings())
node2.addClass({'a':true,'b':true,'c':true})
console.log(item3)
修改原型链/Node2无侵入
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
推荐阅读更多精彩内容
- 本篇博客为"高性能JavaScript"一书部分知识点学习笔记摘录. 作用域链及和标识符解析 每一个JavaScr...
- 普通对象和函数对象 函数对象:使用函数声明、函数表达式、Function构造函数创建的对象 函数实际上是对象,每个...