首页 > 解决方案 > jquery不接受属性,导致给定字符串而不是对象

问题描述

描述:

我尝试动态获取 HTML-Object 的值。所以我在 Object 上写了一个原型函数select 。它在控制台上工作,但不在脚本中。一个 jquery 属性有一些反对它的东西。

错误:

Uncaught TypeError: can't assign to property "guid" on "innerText": not an object

相关对象的输出:

Object { 0: th, 1: th, 2: th, 3: th, 4: th, 5: th, length: 6, prevObject: {…} }

对象上的功能选择:

Object.prototype.select = function(what)
{
    return this.map(function() {
        return this[what];
    }).get();
}

电话:

label.select('innerText')

这是一个已知的错误吗?有解决方法吗?调试器只是与 jquery 中的一个点有关:

S.find.matchesSelector(re,i),n.guid||(n.guid=S.guid++)

已经解决了:

function getData(data)
{
    return $(data).map(function() {
        return this.value;
    }).get();
}

标签: javascriptjqueryobjecthtml-object

解决方案


向对象添加属性绝不是一个好主意Object.prototype。用这样的简单赋值来添加它们是一个特别糟糕的主意,这样它们就可以枚举了。此外,查看select函数的内容,请注意几乎没有对象具有map方法。(数组是唯一的内置对象map。jQuery 对象也有它。)

我强烈建议不要在Object.prototype.

但是,如果你仍然这样做,请添加 *non-enumerable`:

Object.defineProperty(Object.prototype, "select", {
    value() {
        // ...your code here
    },
    writable: true,
    configurable: true,
});

仍然不是一个好主意,因为库拥有自己的专用对象并不少见,这些对象很可能有一个select方法(例如,jQuery 对象),为您设置冲突。但至少如果你使它不可枚举,该属性将不会出现在for-in循环和类似的情况下。


推荐阅读