Are there legitimate uses for JavaScript's “with” statement?

后端 未结 30 1772
伪装坚强ぢ
伪装坚强ぢ 2020-11-22 04:22

Alan Storm\'s comments in response to my answer regarding the with statement got me thinking. I\'ve seldom found a reason to use this particular language feature, and had ne

30条回答
  •  醉话见心
    2020-11-22 05:12

    I created a "merge" function which eliminates some of this ambiguity with the with statement:

    if (typeof Object.merge !== 'function') {
        Object.merge = function (o1, o2) { // Function to merge all of the properties from one object into another
            for(var i in o2) { o1[i] = o2[i]; }
            return o1;
        };
    }
    

    I can use it similarly to with, but I can know it won't affect any scope which I don't intend for it to affect.

    Usage:

    var eDiv = document.createElement("div");
    var eHeader = Object.merge(eDiv.cloneNode(false), {className: "header", onclick: function(){ alert("Click!"); }});
    function NewObj() {
        Object.merge(this, {size: 4096, initDate: new Date()});
    }
    

提交回复
热议问题