js create实现
使用 document.createElement() 创建 DOM 元素
通过 document.createElement() 方法可以动态创建 HTML 元素。该方法接受一个字符串参数,指定要创建的标签名称,返回一个新创建的 DOM 元素。
const divElement = document.createElement('div');
divElement.textContent = 'This is a new div';
document.body.appendChild(divElement);
创建的元素不会自动添加到文档中,需要使用 appendChild() 或类似方法将其插入到 DOM 树中。
使用 new 关键字创建对象实例
在 JavaScript 中,可以通过构造函数和 new 关键字创建对象实例。构造函数通常以大写字母开头。
function Person(name, age) {
this.name = name;
this.age = age;
}
const person = new Person('Alice', 30);
console.log(person.name); // 输出: Alice
ES6 引入了类语法,使得对象创建更加清晰:
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
}
const person = new Person('Bob', 25);
使用 Object.create() 创建对象
Object.create() 方法创建一个新对象,使用现有的对象作为新创建对象的原型。

const prototypeObj = {
greet() {
console.log(`Hello, ${this.name}`);
}
};
const newObj = Object.create(prototypeObj);
newObj.name = 'Charlie';
newObj.greet(); // 输出: Hello, Charlie
这种方法允许实现纯净的原型继承,而不需要构造函数。
使用工厂函数创建对象
工厂函数是返回新对象的函数,可以封装对象创建逻辑。
function createUser(name, email) {
return {
name,
email,
getInfo() {
return `${this.name} <${this.email}>`;
}
};
}
const user = createUser('Dave', 'dave@example.com');
console.log(user.getInfo());
工厂函数模式避免了使用 new 关键字和 this 绑定问题。

使用 Array.from() 创建数组
Array.from() 方法从类数组或可迭代对象创建新数组。
const str = 'hello';
const charArray = Array.from(str);
console.log(charArray); // 输出: ['h', 'e', 'l', 'l', 'o']
const set = new Set([1, 2, 3]);
const arrayFromSet = Array.from(set);
console.log(arrayFromSet); // 输出: [1, 2, 3]
这个方法还可以接受映射函数作为第二个参数:
const numbers = [1, 2, 3];
const doubled = Array.from(numbers, x => x * 2);
console.log(doubled); // 输出: [2, 4, 6]
使用 new Array() 创建数组
虽然不推荐,但可以使用 new Array() 构造函数创建数组。
const emptyArray = new Array(); // 创建空数组
const sizedArray = new Array(5); // 创建长度为5的空数组
const filledArray = new Array(1, 2, 3); // 创建包含元素的数组
这种方法容易引起混淆(特别是单个数字参数时),建议使用数组字面量 [] 替代。






