with 的功能強大,但因為爭議的關係在未來使用於程式碼中的機會不大,但可以看看他如何在各實作中呈現,例如測試或樣板等等。
with(doucment.body.style) {
backgroundRepeat = "no-repeat";
backgroundImage = "url(http://ie7-js.googlecode.com/svn/trunk/lib/blank.gif)"
backgroundAttachment = "fixed"
}
with (YAHOO.util.Dom) {
YAHOO.util.Event.on([get('item'), get('otheritem')], 'click', function(){ setStyle(this, 'color', '#c00')})
}
new Test.Unit.Runner({
testSliderBasics: function(){
with(this){
var slider = new Control.Slider('handle1', 'track1');
assertInstanceOf(Control.Slider, slider);
assertEqual('horizontal', slider.axios);
assertEqual(false, slider.disabled);
assertEqual(0, slider.value);
slider.dispose();
}
},
// ...
})
(function(){
var cache = {};
this.tmpl = function tmpl(str, data){
var fn !/\W/.test(str) ? cache[str] = cache[str] || tmpl(document.getElementById(str).innerHTML) :
new Function("obj",
"var p=[], print=function(){p.push.apply(p,arguments);};" +
"with(obj){p.push('" +
str
.replace(/[\r\t\n]/g, " ")
.splite("<%").join("\t")
.replace(/((^|%>)[^\t]*)'/g, "$1\r")
.replace(/\t=(.*?)%>/g, "',$1,'")
.splite("\t").join("');")
.splite("%>").join("p.push('")
.splite("\r").join("\\'")
+ "');} return p.join('');");
return data ? fn(data) : fn;
};
})()
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Statements/with