JavaScript 为 Function 增加方法,为什么不行?
本文介绍了JavaScript 为 Function 增加方法,为什么不行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
<div id="a"></div>
<script>
function K(a,b){
return b=='css'?document.querySelectorAll(a):(
b=='tag'?document.getElementsByTagName(a):(
b=='class'?document.getElementsByClassName(a):
document.getElementById(a) ))
}
Function.prototype.html=function (a) {this.innerHTML=a}
K("a").html("1");
</script>
第一次接触这些东西,不解。
本人知道语法有很大错误,但 Google Baidu 了很久, W3Schools 能看懂的部分也没写。
望指教!
解决方案
Function.prototype.html=function (a) {this.innerHTML=a}
这句其实是给Function
类的对象添加方法 html
,哪些属于Function
类呢? 所有函数属于Function
类.
Function.prototype.html=function (a) {console.log("HTML method is called")}
function K() {}
K.html();
这样的代码才是能工作的。
你的代码中K("a")
返回的不是一个函数而是一个NodeList
或者HTMLElement
类型的数据,他们都不属于Function
类,所以不能访问添加给 Function
类的方法。
所以要给NodeList
和HTMLElement
添加你想要的方法(或者你自己在K函数中统一成某种相同的类型,就像jQuery做的那样,就不写例子了)
NodeList.prototype.html = function(str){
var i;
for(i=0;i<this.length;i++){
this.item(i).innerHTML=str;
}
}
HTMLElement.prototype.html = function(str){
var i;
this.innerHTML = str;
}
K("a").html("1");
这篇关于JavaScript 为 Function 增加方法,为什么不行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文