gpt4 book ai didi

javascript - Object.defineProperty chrome devtool下不可见的prop

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

好吧,我在尝试使用 Object.watch 的 polyfill 时遇到了问题在 Chrome 中。 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/watch https://gist.github.com/eligrey/384583

polyfill 非常短,您可以阅读它如何删除原始属性并立即定义一个具有相同值但覆盖 getter 和 setter 的新属性。

问题是,如果你使用这个 polyfill 并在 o.p 上观看:

var o = { p: 1 };
o.watch("p", function (id, oldval, newval) {
console.log( "o." + id + " changed from " + oldval + " to " + newval );
return newval;
});

之后检查对象 o在 chrome 开发工具下。砰!对象 o现在是空的!实际上它还有属性p , 输入 o.p你会发现o.p = 1 .

我的问题是,为什么该属性在 Chrome 开发者工具对象属性列表下是不可见的?

注意:如果您对 Object.watch 不了解/不感兴趣,你可能仍然可以帮助我解决这个问题,只要你理解Object.defineProperty好吧。


编辑:事实证明它与我想象的完全不同,它创建了一个新属性,只是覆盖了它的 getter 和 setter。引自 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty“对象中的属性描述符有两种主要类型:数据描述符和访问器描述符。数据描述符是具有值的属性,该值可能可写,也可能不可写。访问器描述符是由 getter-setter 对描述的属性的功能。”

所以看起来 polyfill 将目标属性从“数据属性”更改为“访问器属性”。我认为唯一的填充方法是什么?

最佳答案

My question is, why the property is invisible under Chrome developer tools object property list?

答案是:它是可见的,但现在它是一个getter和setter。

Object {}
get p: function () {
set p: function (val) {
__proto__: Object

jsfiddle

如果您问为什么看不到它的值:那是因为该值现在是私有(private)的,只能使用 getter 读取。

console.log(o.p);

更新:阅读Mutator method

Mutator method

From Wikipedia, the free encyclopedia

In computer science, a mutator method is a method used to control changes to a variable. They are also widely known as '''setter''' methods. Often a setter is accompanied by a '''getter''' (also known as an accessor), which returns the value of the private member variable. The mutator method, sometimes called a "setter", is most often used in object-oriented programming, in keeping with the principle of encapsulation. According to this principle, member variables of a class are made private to hide and protect them from other code, and can only be modified by a public member function (the mutator method), which takes the desired new value as a parameter, optionally validates it, and modifies the private member variable.

考虑这个例子

function MyClass() {
var privateVar = 0;

this.getPrivate = function () {
return privateVar;
}

this.setPrivate = function (value) {
privateVar = value;
}
}

var newObject = new MyClass();

console.log(newObject);

console.log(newObject.getPrivate());

输出

MyClass {getPrivate: function, setPrivate: function}
getPrivate: function () {
setPrivate: function (value) {
__proto__: MyClass

0

jsfiddle

您可以查看对象并查看公共(public)方法 getPrivatesetPrivate(类似于 Object.defineProperty 创建的真实 getter 和 setter) ,但是看不到成员变量privateVariable的值。您只能通过调用 getPrivate 公共(public)方法来查看该值。

关于javascript - Object.defineProperty chrome devtool下不可见的prop,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17718188/

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