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

前端 未结 2 1609
迷失自我
迷失自我 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:35

    If you want to put the properties of the object in the scope of the function, you can extend the scope by using with:

    function a(options) {
        with(options) {
            // properties of `options` are in the scope
            alert(abc);
        }
    }
    

    Disclaimer: Make sure you read the documentation and about disadvantages of with. It should be avoided and is also kind of deprecated:

    Using with is not recommended, and is forbidden in ECMAScript 5 strict mode. The recommended alternative is to assign the object whose properties you want to access to a temporary variable.

    So the questions is why not stick with options ?

提交回复
热议问题