gpt4 book ai didi

javascript - 如何使对象在 Javascript 中可订阅?

转载 作者:行者123 更新时间:2023-12-05 09:11:50 25 4
gpt4 key购买 nike

在 Python 中,我可以通过在类中实现 __getitem__ 方法使对象可订阅:

class Room:
def __init__(self, furniture):
self.furniture = furniture

def __getitem__(self, index):
return self.furniture[index]

furniture = ['chair', 'TV', 'bed']
room = Room(furniture)
print(room[1]) # prints TV

因此,我可以仅通过提供索引来检索项目。

我可以在 Javascript 中实现相同的功能吗?目前我需要显式调用 getitem 方法:

class Room {
constructor(furniture) {
this.furniture = furniture
}

getitem(index) {
return this.furniture[index]
}
}

let furniture = ['chair', 'TV', 'bed']
let room = new Room(furniture)
console.log(room.getitem(1))

最佳答案

如果你想从数组中动态访问数字属性,你可以使用 Proxy使用 get trap 为您的对象拦截对数字属性的调用并将它们重定向到 getitem 方法:

class Room {
constructor(furniture) {
this.furniture = furniture
}

getitem(index) {
return this.furniture[index]
}
}

const handler = {
get: function(target, prop, receiver) {
const numericProp = Number(prop);

//verify the property is actually an integer
if (Number.isInteger(numericProp)) {
return target.getitem(numericProp);
} else {
//return what would be normally returned
return Reflect.get(...arguments);
}
}
}

let furniture = ['chair', 'TV', 'bed']
let room = new Room(furniture)

const proxy = new Proxy(room, handler);
console.log(proxy[0]);// chair
console.log(proxy[1]);// TV
console.log(proxy[2]);// bed
console.log(proxy[3]);// undefined

room.furniture.push("table");

console.log(proxy[3]);// table

console.log(proxy.furniture); //["chair", "TV", "bed", "table"]

您还可以使用 construct trap拦截 new 关键字并返回已经代理的对象:

class Room {
constructor(furniture) {
this.furniture = furniture
}

getitem(index) {
return this.furniture[index]
}
}

const numericGetHandler = {
get: function(target, prop, receiver) {
const numericProp = Number(prop);

//verify the property is actually an integer
if (Number.isInteger(numericProp)) {
return target.getitem(numericProp);
} else {
//return what would be normally returned
return Reflect.get(...arguments);
}
}
}

const constructProxyHandler = {
construct(target, args) {
//call the constructor normally
const instance = new target(...args);

//return a proxy
return new Proxy(instance, numericGetHandler);
}
};

const ProxyRoom = new Proxy(Room, constructProxyHandler);

let furniture = ['chair', 'TV', 'bed']
let room = new ProxyRoom(furniture)

console.log(room instanceof Room); //true

console.log(room[0]);// chair
console.log(room[1]);// TV
console.log(room[2]);// bed
console.log(room[3]);// undefined

room.furniture.push("table");

console.log(room[3]);// table

console.log(room.furniture); //["chair", "TV", "bed", "table"]

由于 Proxy 本质上是透明的,如果您使用的是模块,则只需执行 export new Proxy(Room, constructProxyHandler) 即可,因此在导入时,您无需了解或关心涉及代理。您只需从“room.js”导入 Room 并正常对待 Room

关于javascript - 如何使对象在 Javascript 中可订阅?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59662891/

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