array.protype正在应用于非阵列对象(?)

问题描述 投票:0回答:1

我有一个库,其中添加了以下数组类型-

Array.prototype.top = function() {
    return (this.length > 0) ? this[this.length-1] : null;
    }
它似乎应用于非阵列对象 - 例如,

for (key in myrecordset) { alert(key); // will iterate and alert "top"; }
在调试器控制台:

> myrecordset.length < undefined > typeof myrecordset < 'object' > myrecordset instanceof(Array) < false > myrecordset['top'] < f() { return (this.length ... }
,什么?
该对象不是JavaScript数组
(即没有长度,不是...的实例),但是Array.prototype.top似乎已应用?

注:此外,尝试遵循原型链,我得到了

> myrecordset.constructor() < {} [[ Prototype ]]: Object

Scope:用myrecordset屏幕截图

enter image description here

对象可能会获得等于
javascript arrays object prototype
1个回答
0
投票
的属性的多种方式。

这里是一种可能的情况:

Array.prototype.top = function () { return this.at(-1) ?? null } console.log([1,2,3].top()); // 3 class RecordSet { constructor(...items) { Object.assign(this, items); Object.assign(this, Array.prototype); } } const myrecordset = new RecordSet({a:1}, {b:2}); console.log("top" in myrecordset); // true console.log(myrecordset.length); // undefined console.log(typeof myrecordset); // object console.log(myrecordset instanceof Array); // false console.log(myrecordset.top === Array.prototype.top); // true console.log(myrecordset); // "0": .. "1": .. "top": ..


一种可能防止这种情况的方法是将
top

定义为阵列原型上的不可能量属性:


Object.defineProperty(Array.prototype, "top", { configurable: true, writable: true, value() { return this.at(-1) ?? null } }); console.log([1,2,3].top()); // 3 class RecordSet { constructor(...items) { Object.assign(this, items); Object.assign(this, Array.prototype); } } const myrecordset = new RecordSet({a:1}, {b:2}); console.log("top" in myrecordset); // false console.log(myrecordset.top); // undefined console.log(myrecordset); // "0": .. "1": ..


    

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.