简体   繁体   English

为什么 Object class 主要使用 static 方法,而数组 ZA2F2ED4F8EBC2CBB14C21A29DZ 主要使用实例方法?

[英]Why is the Object class using mostly static methods while the Array class is mostly having instance methods?

I am wondering why, when working with arrays I usually work with instance methods such as .split , .indexOf , .map while when working with objects, I mostly use static methods on the Object class? I am wondering why, when working with arrays I usually work with instance methods such as .split , .indexOf , .map while when working with objects, I mostly use static methods on the Object class?

I count 21 static methods for the Object class , and just 3 for Arrays , of which 2 are concerned with creation rather than manipulation. I count 21 static methods for the Object class , and just 3 for Arrays , of which 2 are concerned with creation rather than manipulation.

The only explanation I can come up with, is that since everything inherits from Object in JS, the designers wanted to keep those Object objects as lightweight as possible.我能想出的唯一解释是,由于所有东西都继承自 JS 中的 Object,因此设计人员希望使这些 Object 对象尽可能轻量级。

The only explanation I can come up with, is that since everything inherits from Object in JS, the designers wanted to keep those Object objects as lightweight as possible.我能想出的唯一解释是,由于所有东西都继承自 JS 中的 Object,因此设计人员希望使这些 Object 对象尽可能轻量级。

That's it exactly.就是这样。 You don't want to fill up Object.prototype with a bunch of methods, because they'd be on everything that's an object (or at least, everything that's an object that inherits from Object.prototype , which all objects do by default though you can prevent it with Object.create ). You don't want to fill up Object.prototype with a bunch of methods, because they'd be on everything that's an object (or at least, everything that's an object that inherits from Object.prototype , which all objects do by default though您可以使用Object.create来阻止它)。

There's a second, more subtle reason: Because you don't want basic operations altered by objects in the general case.还有第二个更微妙的原因:因为在一般情况下,您不希望对象更改基本操作。 That's one reason you see people avoiding using the hasOwnProperty method on an object and instead using it directly from Object.prototype :这就是你看到人们避免在 object 上使用hasOwnProperty方法,而是直接从Object.prototype使用它的原因之一:

if (Object.prototype.hasOwnProperty.call(obj, "name")) {
    // ...
}

The author of the code above wanted to avoid the possibility that hasOwnProperty had been redefined for obj such that it would lie.上面代码的作者想要避免hasOwnProperty已经为obj重新定义的可能性,这样它就会撒谎。 :-) :-)

 const obj = { hasOwnProperty() { return true; } }; console.log(obj.hasOwnProperty("foo")); // true console.log(Object.prototype.hasOwnProperty.call(obj, "foo")); // false, which is correct

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM