返回
手写一个New函数
前端
2023-11-25 11:54:59
深入剖析:手把手实现New函数
作为一名javascript开发者,掌握New函数的底层实现原理至关重要。New函数是一个神奇的工具,它允许我们创建自定义类型并为其分配内存空间。在本篇文章中,我们将详细剖析如何手动实现一个New函数,深入理解其工作机制。
1. 创建一个空的、未初始化的对象:
function New(constructorFunction) {
var newObject = {};
newObject.__proto__ = constructorFunction.prototype;
return newObject;
}
2. 绑定构造函数的原型:
function Person(name, age) {
this.name = name;
this.age = age;
}
var person = New(Person);
3. 执行构造函数,得到结果:
Person.call(person, "John", 25);
4. 最终,返回创建的对象:
return person;
代码演示:
function New(constructorFunction) {
var newObject = {};
newObject.__proto__ = constructorFunction.prototype;
var result = constructorFunction.apply(newObject, Array.prototype.slice.call(arguments, 1));
return result ? result : newObject;
}
function Person(name, age) {
this.name = name;
this.age = age;
}
var person1 = New(Person, "John", 25);
var person2 = new Person("Mary", 30);
console.log(person1.name); // "John"
console.log(person2.name); // "Mary"
通过手动实现New函数,我们不仅加深了对JavaScript语言底层的理解,也能够更好地掌握对象创建的机制。