调用 Proxy 对象中的 get 方法而不是 set 方法

我开始研究 JavaScript 代理对象,并遇到了一些奇怪的行为。我正在尝试将一个数字推送到代理数组,但是,出乎我意料的是,get方法被调用(如果存在)!但是,如果我删除get中的方法arrayHandler,set则会按预期调用,并且数字会被推送。为什么可能呢?


class SomeClass {

    public readonly name: String;

    public originalData: Array<number> = [];


    private arrayHandler = {

        set(

            target: Array<number>,

            prop: number,

            val: any,

            reciever: any

        ): boolean {

            console.log("PROXY HANDLER SET");

            target[prop] = val;

            return true;

        },

        get(target: Array<number>, prop: number): void {

            console.log("PROXY HANDLER GET");

        },

    };

    public proxyToArray: any = new Proxy(this.originalData, this.arrayHandler);


    constructor(name: String) {

        this.name = name;

    }

}


let item = new SomeClass("item-1");

item.proxyToArray.push(1);


拉风的咖菲猫
浏览 82回答 1
1回答

哔哔one

您需要在 getter 中返回目标:class SomeClass {&nbsp; &nbsp; public readonly name: String;&nbsp; &nbsp; public originalData: Array<number> = [];&nbsp; &nbsp; private arrayHandler = {&nbsp; &nbsp; &nbsp; &nbsp; set(&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; target: Array<number>,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; prop: number,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; val: any,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; reciever: any&nbsp; &nbsp; &nbsp; &nbsp; ): boolean {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log("PROXY HANDLER SET");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; target[prop] = val;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return true;&nbsp; &nbsp; &nbsp; &nbsp; },&nbsp; &nbsp; &nbsp; &nbsp; get(target: Array<number>, prop: number): any {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log("PROXY HANDLER GET");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return target[prop];&nbsp; &nbsp; &nbsp; &nbsp; },&nbsp; &nbsp; };&nbsp; &nbsp; public proxyToArray: any = new Proxy(this.originalData, this.arrayHandler);&nbsp; &nbsp; constructor(name: String) {&nbsp; &nbsp; &nbsp; &nbsp; this.name = name;&nbsp; &nbsp; }}let item = new SomeClass("item-1");item.proxyToArray.push(1);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript