JS Prototype方法在循环访问时的行为方式不同

Sud*_*lla 0 javascript arrays prototype

我正在使用一个名为的新方法扩展数组对象,custommethod并循环遍历数组中的值.但是,循环索引还会打印通过索引property扩展的名称Array.prototype.<method>.

Array.prototype.custommethod = function() {
    console.log("Hello from Custom Method");
}

Object.defineProperty(Array.prototype, "anothercustommethod", {
    value: function() {
        console.log("Hello from Another Custom Method");
    }
});
Run Code Online (Sandbox Code Playgroud)

循环遍历数组

> x = [1,2]
[ 1, 2 ]

> for (i in x) { console.log(i); }
0
1
custommethod
Run Code Online (Sandbox Code Playgroud)
  • 为什么不在anothercustommethod这个循环中打印?

  • 使用Object.defineProperty()更安全的方式来创建Array.prototype

我很好奇forjavascript中的循环是如何工作的.它在Object.keys()内部使用吗?如果是这样,它如何打印custommethod哪个属于内部__proto__属性但不是anothercustommethod哪个也属于内部__proto__属性?

Sur*_*yan 5

为什么不在另一个习惯方法中打印出这个循环?

for in迭代这些属性,数据描述符enumerable设置为true.

文档中

zhumerable 当且仅当在枚举相应对象的属性期间显示此属性时才为true.默认为false.

使用时defineProperty,您还可以传递额外的属性 - 可枚举.默认情况下,它设置为false.

Array.prototype.custommethod = function() {
    console.log("Hello from Custom Method");
}

Object.defineProperty(Array.prototype, "anothercustommethod", {
    value: function() {
        console.log("Hello from Another Custom Method");
    },
    enumerable: true
});

const x = [1,2]
for (i in x) { console.log(i); }
Run Code Online (Sandbox Code Playgroud)

使用Object.defineProperty()是一种创建Array.prototype的更安全的方法吗?

安全没什么.尝试很少更改原型中的构建