构造函数优缺点分析
function Student(name, age) {
this.name = name;
this.age = age;
this.sayName = function() {
console.log(this.name);
}
}
function Fruit(name, color) {
this.name = name;
this.color = color;
this.sayName = function() {
console.log(this.name);
}
}
var s1 = new Student("李华", 20);
var f1 = new Fruit("苹果", "红色");
console.log(s1);
//Student {name: "李华", age: 20, sayName: ƒ}
console.log(f1);
//Fruit {name: "苹果", color: "红色", sayName: ƒ}
//解决了无法识别对象类型的问题
console.log(s1 instanceof Student); //true
console.log(f1 instanceof Fruit); //true
优点:可复用;可识别对象类型的问题;
缺点:两个构造函数中,定义了同样的方法 sayName,当我们在实例化的时候,这无疑会消耗更多的内存。
解决:将同样的方法提取出来,在全局作用域中进行定义。
function Student(name, age) {
this.name = name;
this.age = age;
this.sayName = sayName;
}
function Fruit(name, color) {
this.name = name;
this.color = color;
this.sayName = sayName;
}
function sayName() {
console.log(this.name);
}
var s1 = new Student("李华", 20);
var f1 = new Fruit("苹果", "红色");
s1.sayName(); //李华
f1.sayName(); //苹果
console.log(s1.sayName == f1.sayName);//true
问题:容易造成全局污染
另外一个问题:其中的每个方法例如sayName(),在每次实例化时都会自动重新创建一遍,产生不同的作用域链,因此即使是同名函数也是不相等的,下面利用上述代码创建两个实例:
function Student(name, age) {
this.name = name;
this.age = age;
this.sayName = function(){
console.log(this.name);
};
}
var s1 = new Student("李华", 20);
var s2 = new Fruit("苹果", 30);
console.log(s1.sayName == s2.sayName);//false
解决:将方法定义在全局作用域中
function Student(name, age) {
this.name = name;
this.age = age;
this.sayName = sayName;
}
function sayName(){
console.log(this.name);
}
var s1 = new Student("李华", 20);
var s2 = new Fruit("苹果", 30);
console.log(s1.sayName == s2.sayName);//true