自定义element.prototype函数有未定义的“this”

时间:2014-04-14 09:17:57

标签: javascript internet-explorer-8

我正在尝试创建一个备份函数,以便在浏览器不支持classList的情况下使用

if(!Element.prototype.classList)    {
  Element.prototype.classList = {};

  Element.prototype.classList.contains =
    function(class_name){
        console.log(this)
    }
}

console.log(this)返回“undefined”,如何获取调用该函数的元素?

1 个答案:

答案 0 :(得分:0)

IE8' console.log()可能是"打破"结果不知何故。在IE8兼容模式的控制台中(在IE11中),这会正确显示[object Object] { }作为返回值,可展开以显示附加的contains()函数:

Element.prototype.classList = {};
Element.prototype.classList.contains = function() {
  return this;
};
var n = document.createElement('div');
n.classList.contains(x);

但是,在console.log()中包含该返回值会显示undefined。只需让它流过"但是,控制台会按预期显示对象。

可能与古老的IE怪癖有关,除非打开开发者工具,否则console不存在?