JavaScript 为 Function 增加方法,为什么不行?
大家讲道理
大家讲道理 2017-04-11 13:21:00
[JavaScript讨论组]

第一次接触这些东西,不解。

本人知道语法有很大错误,但 Google Baidu 了很久, W3Schools 能看懂的部分也没写。
望指教!

大家讲道理
大家讲道理

光阴似箭催人老,日月如移越少年。

全部回复(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");
ringa_lee
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');
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号