How can I *unpack* an object into a function's scope?

前端 未结 2 1517
迷失自我
迷失自我 2021-01-19 09:05

I have this code...

function a(options) {
    for (var item in options) {
       if ( ! options.hasOwnProperty(item)) {
          continue;
       }
       t         


        
2条回答
  •  失恋的感觉
    2021-01-19 09:39

    You can access the function from inside itself using the callee property:

    function a(options) {
        var thiz = arguments.callee;
        for (var item in options) {
            if (!options.hasOwnProperty(item)) {
                continue;
            }
            thiz[item] = options[item];
        }
    }
    
    a({
        'abc': 'def'
    });
    
    alert(a.abc);
    

    Alternatively, you can set the scope when you call it:

    function a(options) {
        for (var item in options) {
            if (!options.hasOwnProperty(item)) {
                continue;
            }
            this[item] = options[item];
        }
    }
    
    a.call(a, {
        'abc': 'def'
    });
    alert(a.abc);
    

提交回复
热议问题