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 能看懂的部分也没写。
望指教!

阅读 2.9k
2 个回答
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类的方法。

所以要给NodeListHTMLElement添加你想要的方法(或者你自己在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");
Function.prototype.html = function(){...}

这是 Function 实例才能够继承的方法。
也就是说:

function K(a , b){ ...}

需要:

   var a = new K('a') 
   a.html('1');

这样才能够奏效。

而直接不实例化对象去调用,则实际上是在调用 返回值的属性/方法。
K('a').html('1') 等价于 :
由于 k('a') 返回的是 document.getElementById('a'),所以等价于:document.getElementById('a').html('1')

才会导致错误发生。

应该:new K('a').html('1') 。

额,代码刚才测试了一下。有点问题...,稍微修改了下哈。

var a = new K('a');
console.log(a intanceof K); // false, 不是 K 的实例。由于 K 有返回值(DOM元素),覆盖了本该返回的 K 的实例。

若是修改 K 函数:
function K(){}

var a = new K();
console.log(a instanceof K); // true,是 k 的实例

所以应该这样:
function K(a , b){
  this.curEle = b=='css'?document.querySelectorAll(a):(
  b=='tag'?document.getElementsByTagName(a):(
  b=='class'?document.getElementsByClassName(a):
  document.getElementById(a) ));
}

K.prototype.html = function(a){this.curEle.innerHTML = a};

new K('a').html('1');
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题