1、for / in
功能:遍历对象属性
可以遍历出对象的原型对象的方法,一般不需要这样,此时:
function Car(id,type,color){
this.type = type;
this.color = color;
this.id = id;
}
var benz = new Car("benz", "black", 12345);
Car.prototype.start = function(){
console.log(this.type + "start");
}
for(var key in benz){
if(benz.hasOwnProperty(key)){
console.log(key + ":" + benz[key]);
}
}
2、with
功能:
-通常用于缩短特定情形下必须写的代码量
-暂时改变变量的作用域链,将with语句中的对象添加到作用域链的头部
示例:
(function(){
var x = Math.cos(3 * Math.PI) + Math.sin(Math.LN10)
var y = Math.tan(14 * Math.E)
})();
等同于:
(function(){
with(Math){
var x = cos(3 * PI) + sin(LN10)
var y = tan(14 * E)
}
})();
缺点:with语句可能导致执行性能下降,应该尽可能的避免使用