javascript - 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();
}
解决方案
向对象添加属性绝不是一个好主意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
循环和类似的情况下。
推荐阅读
- javascript - 在 Reactjs 中上传文件
- android-service - 出现错误尝试使用损坏的通知启动前台服务(xxx)(无图标:通知(pri = 0 contentView = null ---
- php - 无停机 Laravel 部署
- regex - 没有在scala中正确拆分字符串
- python - 我刚刚创建了一个 Python 脚本。我正在尝试在我的 Windows 计算机上运行它。这没用
- python - 尝试在 Spyder (Python 3.7) 上安装新库
- javascript - React - 通过功能组件传递 props up 组件树
- angular - Angular 9 的交互式坐标系
- mysql - nodejs 服务器 app.post 问题 XML 解析错误:语法错误位置:http://localhost:3000/get_messages 第 1 行第 1 列:
- c# - WPF中切换用户控件只显示ViewModel的名称