function ClassA() {
this.weight = 100;
this.age = 0;
}
var classA = ClassA();
console.log(classA); // undefined
console.log(window.weight); // 100
console.log(window.age); // 0
在初始化变量时,如果我们忘记使用 new 关键字,构造函数内的属性将会污染到全局对象上,如果属性名与已有方法名重名时,更会出现难以查找的 bug,现在我们来修改构造函数避免此问题:
function ClassA() {
if (this instanceof ClassA) {
this.weight = 100;
this.age = 0;
}else{
return new ClassA;
}
}
var classA = ClassA();
console.log(classA); // ClassA {weight: 100, age: 0}
console.log(window.weight); // undefined
console.log(window.age); // undefined