1. 实现 new
先看看平时我们是怎么使用new的:
function Person(name, age){
this.name = name;
this.age = age;
}
let person = new Person('zs', 20);
在以上代码中,new实际做了以下几件事:
- 创建一个新对象
- 改变构造函数中的作用域指向:
this指向新对象 - 将构造函数接收的参数,为对象中的属性赋值
- 返回这个对象
分析完,我们就可以动手实现了:
function myNew(Constructor){
return function(){
let obj = new Object();
obj.__proto__ = Constructor.prototype;
Constructor.call(obj, ...arguments);
// Constructor.apply(obj, arguments);
return obj;
}
}
function Person(name, age){
this.name = name || 'zs';
this.age = age || 20;
}
let person1 = myNew(Person)('ls', 18);
let person2 = myNew(Person)();
2. 实现浅拷贝
let obj = {a: 1, b: {c: 2}};
// 1. ...运算符
let newObj = {...obj};
// 2. Object.assign
let newObj = Object.assign({}, obj);
// 3. 自定义simpleCopy函数
function simpleCopy(obj){
let newObj = obj instanceof Array ? [] : {};
// let newObj = Array.isArray(obj) ? [] : {};
// let newObj = obj.constructor.name === "Array" ? [] : {};
for(let i in obj){
newObj[i] = obj[i];
}
return newObj;
}
3. 实现深拷贝
// 1. 自定义deepCopy函数
function deepCopy(obj) {
let newObj = Array.isArray(obj) ? [] : {};
for(let i in obj){
if(obj.hasOwnProperty(i)){
if(obj[i] && typeof obj[i] === "object"){
newObj[i] = deepCopy(obj[i]);
}else{
newObj[i] = obj[i];
}
}
}
return newObj;
}
// 2. JSON.stringify JSON.parse
let newObj = JSON.parse(JSON.stringify(obj));
4. 实现 Array.isArray
Array.myIsArray = function(obj){
return obj.constructor.name === 'Array';
// return Object.prototype.toString.call(obj) === '[object Array]';
}
5. 实现 instanceof
利用while循环,向上查询实例对象的原型链,判断实例对象的原型对象是否等于传入的构造函数的原型对象,直至实例对象的原型为null,返回false
function myInstanceof(obj, constructor){
let protoObj = constructor.prototype;
obj = obj.__proto__;
while(true){
if(obj == null) return false;
if(obj === protoObj) return true;
obj = obj.__proto__;
}
}
本文详细解析并实践了JavaScript中的new操作符的工作原理,以及如何手动实现浅拷贝、深拷贝、Array.isArray和instanceof。通过理解这些基础概念,有助于提升JavaScript编程技能。

被折叠的 条评论
为什么被折叠?



