gpt4 book ai didi

javascript - 对 Object.defineProperties 函数感到困惑

转载 作者:行者123 更新时间:2023-11-28 01:19:17 25 4
gpt4 key购买 nike

所以,我有一个名为 hasClass 的元素原型(prototype)函数。

Element.prototype.hasClass = function (className) 
{
if (className && typeof className === "string")
{
if (this.classList)
{
return this.classList.contains(className);
}
else
{
return new RegExp(className).test("" + this.className + "");
}
}
};

现在,既然我必须定义多个函数,并且代码会变得非常困惑,那么我想,为什么不使用 Object.defineProperties 函数;与以下功能相同的功能:

Object.defineProperties(Element.prototype, {
"hasClass": {
get: function (className)
{
if (className && typeof className === "string")
{
if (this.classList)
{
return this.classList.contains(className);
}
else
{
return new RegExp(className).test("" + this.className + "");
}
}
}
}
});

第一个函数可以正常工作。但是,当使用 Object.defineProperties 定义相同的函数时,我的 Firefox 控制台开始发送垃圾邮件:TypeError: $test.hasClass is not a function (其中 $test 是使用选择器选择的元素)。使用正常的第一个函数示例时不会出现此错误,而使用最新的函数示例时会出现此错误。

所以问题是。为什么它确实会抛出这样的错误,而它不应该抛出这样的错误?

哦,是的,有趣的是,当我将第二个函数与 console.log 一起使用时,如下所示:

Object.defineProperties(Element.prototype, {
"hasClass": {
get: function (className)
{
/*if (className && typeof className === "string")
{
if (this.classList)
{
return this.classList.contains(className);
}
else
{
return new RegExp(className).test("" + this.className + "");
}
}*/
console.log( "HI");
}
}
});

然后控制台显示: /image/K6X2p.png

我很困惑。

最佳答案

您错误地使用了属性get,您应该使用value,否则hasClass将是返回的值 来自 get 函数。

get 替换为 value

Object.defineProperties(Element.prototype, {
"hasClass": {
value: function (className)
{
/*if (className && typeof className === "string")
{
if (this.classList)
{
return this.classList.contains(className);
}
else
{
return new RegExp(className).test("" + this.className + "");
}
}*/
console.log( "HI");
}
}
});

Refer to documentation on defineProperty even though you're using defineProperties

问题:在您的版本中,hasClass 的值将是未定义的,因为您没有从 get 函数返回任何内容,最后一条语句是 console.log( "HI"); 如果你把 return {}; 放在后面,hasClass === {}

关于javascript - 对 Object.defineProperties 函数感到困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23426331/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com