A
A
Artem2018-04-03 21:07:32
JavaScript
Artem, 2018-04-03 21:07:32

How to change the property setter of an object in another function?

How, if necessary, to modify the setter of an object without changing its declaration, if
when using Object.defineProperty this points to the object that called this method?
When trying to use the Object.defineProperty.call(...) function , this still points to the object that called this function.
An example piece of code:

class Foo {
    public ModifySetter(obj: object, field: string): void {
        Object.defineProperty(obj, field, {
            set: (value) => {
                console.log(this); // объект класса Foo
                this[field] = value;
                // some actions
            },
            get: () => this[field]
        });
    }
}

const bar = (field) => {
       Object.defineProperty(this, field, {
            set: (value) => {
                console.log(this); // объект класса Foo
                this[field] = value;
                // some actions
            },
            get: () => this[field]
        });
}

class Foo {
    public ModifySetter(obj: object, field: string): void {
        bar.call(obj, field);
    }
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Artem, 2018-04-04
@Cruper

Changing the context inside a class method does not work. (Features of compiling typescript to js, ​​as I understand it).
However, it is possible to change the context when a class method is called.

C
Coder321, 2018-04-03
@Coder321

class Foo {
    constructor() {
        this._field = '';
    }

    set field(value) {
        this._field = value+='Foo';
    }

    get field() {
        return this._field;
    }
}

class MyFoo extends Foo {
    set field(value) {
        super.field = value;
        this._field += 'MyFoo';
    }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question