Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

要求⽤不同⽅式对 A 进⾏改造实现 A.name 发⽣变化时⽴即执⾏ A.getName #329

Open
lgwebdream opened this issue Jul 6, 2020 · 2 comments
Labels
JavaScript teach_tag 新东方 company 编程题 teach_tag

Comments

@lgwebdream
Copy link
Owner

/*
	已知对象A = {name: 'sfd', getName: function(){console.log(this.name)}},
	现要求⽤不同⽅式对A进⾏改造实现A.name发⽣变化时⽴即执⾏A.getName
*/
@lgwebdream lgwebdream added JavaScript teach_tag 新东方 company 编程题 teach_tag labels Jul 6, 2020
@lgwebdream
Copy link
Owner Author

扫描下方二维码,获取答案以及详细解析,同时可解锁800+道前端面试题。

@GolderBrother
Copy link

// 方法一
let _name = '123';
const A = {
    get name(){
        return _name
    },
    set name(name){
        _name = name;
        this.getName();
    },
    getName() {
        console.log(this.name);
    }
}
A.name = 'james';
A.name = 'robin';

// 方法二
function defineReactive(obj, key, val) {
    if (typeof obj !== 'object' || obj === null) return;
    Object.defineProperty(obj, key, {
        get() {
            return val;
        },
        set(newVal) {
            if (newVal === val) return;
            val = newVal;
            typeof obj.getName === 'function' && obj.getName();
        }
    });
}

const A = { name: 'sfd', getName: function () { console.log(this.name) } };
defineReactive(A, 'name');
A.name = 'james';
A.name = 'robin';
// james
// robin

// 方法三
const A = { name: 'sfd', getName: function () { console.log(this.name) } };
function defineReactive(obj, customKey, val) {
    const handler = {
        get(target, key, receiver) {
            const res = Reflect.get(target, key, receiver);
            return res;
        },
        set(target, key, value, receiver) {
            const res = Reflect.set(target, key, value, receiver);
            if (key === customKey && typeof obj.getName === 'function') obj.getName();
            return res;
        }
    };
    const observer = new Proxy(obj, handler);
    return observer;
}
const _A = defineReactive(A, 'name');
_A.name = 'james';
_A.name = 'robin';
// james
// robin

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
JavaScript teach_tag 新东方 company 编程题 teach_tag
Projects
None yet
Development

No branches or pull requests

2 participants