gpt4 book ai didi

原型(prototype)中值类型的javascript属性

转载 作者:行者123 更新时间:2023-11-29 22:03:55 27 4
gpt4 key购买 nike

我的理解是相同类型的所有对象将共享相同的原型(prototype)。因此对原型(prototype)的更改将反射(reflect)在每个对象上。但是值类型的属性似乎不是这样。这种属性是如何存储的?

function Person() {        
}

Person.prototype.name = "John";
var p1 = new Person();
p1.name = "Luke";
var p2 = new Person();
p2.name = "Mary";

console.log(p1.name); // Luke instead of Mary
console.log(p2.name); // Mary

如果我想实现相同类型的对象计数。最好的方法是什么?在其他 OO 语言中,您通常只需使用静态成员即可。

enter image description here

最佳答案

原型(prototype)属性访问是不对称

  • 当你获得一个属性时 - 如果对象没有它,它将从原型(prototype)中获取它。这是 specified作为:
  1. Let proto be the value of the [[Prototype]] internal property of O.
  2. If proto is null, return undefined.
  3. Return the result of calling the [[GetProperty]] internal method of proto with argument P.
  • 当您设置属性时 - 您总是将其设置在对象上而不是原型(prototype)上。如指定here .

说明:

 var proto = {x:4};
var child = Object.create(proto); // create object with prototype set to `proto`
child.x; // 4, fetched from prototype
child.x = 10;
child.x; // 10, fetched from child
proto.x; // 4, setting on child did not change the prototype
Object.getPrototypeOf(child).x = 6; // you can get around it, and set on the proto.

您可以在 Steve Yegge's excellent "the universal design pattern" 中阅读更多相关信息,以及它为何以这种方式工作.

关于原型(prototype)中值类型的javascript属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22042652/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com