Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

实现call、apply、bind方法 #11

Open
akeymo opened this issue Feb 11, 2020 · 0 comments
Open

实现call、apply、bind方法 #11

akeymo opened this issue Feb 11, 2020 · 0 comments

Comments

@akeymo
Copy link
Owner

akeymo commented Feb 11, 2020

// 实现call方法
Function.prototype.myCall = function (context, ...args) {
    context = context || window;

    // 利用Symbol防止覆盖原有属性
    const fn = Symbol('临时属性');

    // 通过对象属性的形式去调用函数,那么这个函数的this就会指向这个对象即context
    context[fn] = this;
    const result = context[fn](...args);

    delete context[fn];
    return result;
}

// 实现apply方法,原理同call,只是第二个参数是数组形式
Function.prototype.myApply = function (context, args) {
   context = context || window;
    const fn = Symbol('临时属性');
    context[fn] = this;
    const result = context[fn](...args);
    delete context[fn];
    return result;
}

// 实现bind方法
// bind返回一个新函数
// 通过new调用bind返回的函数,原本提供的this值被忽略
Function.prototype.myBind = function (context, ...params) {
    const that = this;

    const fToBind = function (...secondParams) {
        // 判断this是否是fToBind的实例,如果是则表示是通过new调用
        const isNew = this instanceof fToBind;
        // 如果是通过new调用,则原本提供的this值即context被忽略
        context = isNew ? this : context;
        return that.call(context, ...params, ...secondParams);
    }
    // 修改返回函数的prototype为绑定函数的prototype,实例就可以继承绑定函数的原型中的值
    fToBind.prototype = Object.create(that.prototype);
    return fToBind;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant