手写题

Mr.ZhaoAbout 2 min

2. 标签相关操作

1. 获取标签

document.getElementById('id')// 全局唯一
document.getElementByClassName('className')// 获得数组
document.getElementByTagName('div')// 获得数组

2. 插入标签

let head = document.head;
let style = document.createElement('style');
style.type = 'text/css';
style.innerHTML = 'p {color: red;}';
head.appendChild(style);

3. 让盒子充满屏幕

div{
    background-color:red;
    width:100vw;
    height:100vh;
}

4. 手写Object.create

Object.create() 静态方法以一个现有对象作为原型(prototype),创建一个新对象

思路:将传入的对象作为原型(prototype)

function myCreate(obj) {
    // 定义一个构造函数
    function F() {} 
    // 给构造函数的原型赋值
    F.prototype = obj; 
    // 返回构造函数的实例
    return new F(); 
}

示例:

let person = { age: 18 };

let child = Object.create(person);
console.log(child);

let child1 = myCreate(person);
console.log(child1);

5. 手写instanceof方法

instanceof 运算符用于检测构造函数的 prototype 属性是否出现在某个实例对象的原型链上

function myInstanceof(target, origin) {
    const op = origin.prototype;
    let tp = target.__proto__;
    while (true) {
        if (tp === null) {
            return false;
        }
        if (tp === op) {
            return true;
        }
        tp = tp.__proto__;
    }
}

示例:

let arr = [1, 2, 3];
console.log(myInstanceof(arr, Array));

6. 手写new操作符

在调用 new 的过程中会发生以下四件事情:

  1. 首先创建了一个新的空对象
  2. 设置原型,将对象的原型设置为函数的 prototype 对象
  3. 让函数的 this 指向这个对象,执行构造函数的代码(为这个新对象添加属性)
  4. 判断函数的返回值类型,如果是值类型,返回创建的对象。如果是引用类型,就返回这个引用类型的对象
function myNew(constructor, ...args) {
    // 新建一个空对象
    const obj = {};
    // 对象原型为构造函数的prototype
    obj.__proto__ = constructor.prototype;
    // 将this指向新建对象
    const result = constructor.apply(obj, args);
    // 判断函数的返回值类型,如果是值类型,返回创建的对象。如果是引用类型,就返回这个引用类型的对象
    if (
        result &&
        (typeof result === 'object' || typeof result === 'function')
    ) {
        return result;
    }
    return obj;
}

示例:

function Person(name, age) {
    this.name = name;
    this.age = age;
}

console.log(new Person('李四', 18));
console.log(myNew(Person, '张三', 19));

7. 手写promise

详见:手写Promiseopen in new window