1. 创建对象的多种方式&优缺点
1.1 工厂模式
function createPerson(name) {
var o = new Object();
o.name = name;
o.getName = function () {
console.log(this.name);
};
return o;
}
var person1 = createPerson('kevin');
优点:简单;
缺点:对象无法识别,因为所有的实例都指向一个原型;
1.2 构造函数模式
function Person(name) {
this.name = name;
this.getName = getName;
}
function getName() {
console.log(this.name);
}
var person1 = new Person('kevin');
解决了每个方法都要重新创建的问题
1.3 原型模式
function Person(name) {
}
Person.prototype.name = 'xianzao';
Person.prototype.getName = function () {
console.log(this.name);
};
var person1 = new Person();
优点:方法不会重新创建;
缺点:
1. 所有的属性和方法都共享;
2. 不能初始化参数;
1.3.1 原型模式优化
function Person(name) {
}
Person.prototype = {
name: 'xianzao',
getName: function () {
console.log(this.name);
}
};
var person1 = new Person();
优点:封装清晰点;
缺点:重写了原型,丢失了constructor属性;
1.3.2 原型模式优化
function Person(name) {
}
Person.prototype = {
constructor: Person,
name: 'kevin',
getName: function () {
console.log(this.name);
}
};
var person1 = new Person();
优点:实例可以通过constructor属性找到所属构造函数;
缺点:
1. 所有的属性和方法都共享;
2. 不能初始化参数;
1.4 组合模式
function Person(name) {
this.name = name;
}
Person.prototype = {
constructor: Person,
getName: function () {
console.log(this.name);
}
};
var person1 = new Person();
优点:该共享的共享,该私有的私有,使用最广泛的方式;
缺点:希望写在一个地方,即更好的封装性;
2. 继承多种方式&优缺点
2.1 原型继承
// ----------------------方法一:原型继承
// 原型继承
// 把父类的实例作为子类的原型
// 缺点:子类的实例共享了父类构造函数的引用属性 不能传参
var person = {
friends: ["a", "b", "c", "d"]
}
var p1 = Object.create(person)
p1.friends.push("aaa")//缺点:子类的实例共享了父类构造函数的引用属性
console.log(p1);
console.log(person);//缺点:子类的实例共享了父类构造函数的引用属性
2.2 组合继承
// ----------------------方法二:组合继承
// 在子函数中运行父函数,但是要利用call把this改变一下,
// 再在子函数的prototype里面new Father() ,使Father的原型中的方法也得到继承,
// 最后改变Son的原型中的constructor
// 缺点:调用了两次父类的构造函数,造成了不必要的消耗,父类方法可以复用
// 优点可传参,不共享父类引用属性
function Father(name) {
this.name = name
this.hobby = ["篮球", "足球", "乒乓球"]
}
Father.prototype.getName = function () {
console.log(this.name);
}
function Son(name, age) {
Father.call(this, name)
this.age = age
}
Son.prototype = new Father()
Son.prototype.constructor = Son
var s = new Son("ming", 20)
console.log(s);
2.3 寄生组合继承
// ----------------------方法三:寄生组合继承
function Father(name) {
this.name = name
this.hobby = ["篮球", "足球", "乒乓球"]
}
Father.prototype.getName = function () {
console.log(this.name);
}
function Son(name, age) {
Father.call(this, name)
this.age = age
}
Son.prototype = Object.create(Father.prototype)
Son.prototype.constructor = Son
var s2 = new Son("ming", 18)
console.log(s2);
2.4 ES6的extend
// ----------------------方法四:ES6的extend(寄生组合继承的语法糖)
// 子类只要继承父类,可以不写 constructor ,一旦写了,constructor 中的第一句话
// 必须是 super 。
class Son3 extends Father { // Son.prototype.__proto__ = Father.prototype
constructor(y) {
super(200) // super(200) => Father.call(this,200)
this.y = y
}
}
原文参考:前端面试题2021及答案-CSDN博客