1.new实现的过程
function newFun(Fun, ...args) {
let newObj = {};
newObj.__proto__ = Fun.prototype;
const result = Fun.apply(newObj, args);
return result instanceof Object ? result : newObj;
}
function Person(name) {
this.name = name;
}
Person.prototype.say = function () {
console.log("hello world");
};
const p1 = newFun(Person, "yizhiyang");
p1.say();
console.log(p1);
2.递归实现深拷贝
let origin = {
name: "张三",
age: 18,
say() {
console.log("say hello");
},
arr: [[1, 2], 3, 4, 5],
school: {
className: {
userName: "yizhiyang",
},
},
};
function deepClone(origin) {
let newObj = {};
if (typeof origin !== "object" || origin == null) {
return origin;
}
newObj = origin instanceof Array ? [] : {};
for (let key in origin) {
let value = origin[key];
newObj[key] = typeof value === "object" ? deepClone(value) : value;
}
return newObj;
}
const newOrigin = deepClone(origin);
console.log(origin);
console.log(newOrigin);
3. 原型链的继承
- 原型链继承涉及到构
造函数、原型和实例三的关系
- 每一个构造函数都有一个原型对象
- 原型对象又包含一个指向构造函数的指针
- 实例则包含一个原型对象的指针
function Parent() {
this.isShow = true;
this.info = {
name: "yizhiyang",
age: 18,
};
}
Parent.prototype.getInfo = function () {
console.log(this.info);
};
function Child() {}
Child.prototype = new Parent();
let child1 = new Child();
child1.getInfo();
console.log("child1", child1);
let child2 = new Child();
child1.info.gender = "男";
child2.isShow = false;
console.log("child2", child2);
- 让一个构造函数的原型是另一个类型的实例,那么这个构造函数new出来的实例就具有该实例的属性。
- 优点:写法方便简洁,容易理解。
- 缺点:对象实例共享所有继承的属性和方法。无法向父类构造函数传参。