闭包,作用域上下文,面向对象等;

82 阅读1分钟

闭包:

闭包是指有权访问另一个函数作用域中的变量的函数, 创建闭包的常见形式是在一个函数内部创建并返回另一个函数。

this:

函数直接调用 - this指向是window/全局

隐式绑定 - this的指向是调用堆栈的上一级

 

简易手写bind和apply


    // 1. 需求:手写bind => bind位置 => Function.prototype => 原型

    Function.prototype.newBind = function() {

        // 2. bind改变原理

        const _this = this;

        const args = Array.prototype.slice.call(arguments);

        const newThis = args.shift();

 

        // 核心封装函数不执行

        return function() {

            // 执行核心apply

            return _this.newApply(newThis, args);

        }

    }

 

    // 2. 内层实现

    Function.prototype.newApply = function(context) {

        if (typeof this !== 'function') {

            throw new TypeError('Error');

        }

 

        // 参数兜底

        context = context || window;

 

        // 临时挂载执行函数

const fnName=Symbol('fn')

        context[fnName]= this;

 

        let result = arguments[1]

            ? context[fnName](...arguments[1])

            : context[fnName]();

 

        delete context[fnName];

        return result;

    }

 

 

 

 

 

__proto__仿真

 


findProperty(obj,property){

    if(obj.hasOwnProperty(property)){

        return obj[property];

    }

    var __proto__ = obj.__proto__;

    while(__proto__){

        if(__proto__.hasOwnProperty(property)){

            return __proto__[property]

        }

        __proto__ = __proto__.__proto__;

    }

    return undefined

}


var a = 10;
var foo = {
   a: 20,
   bar: function () {
      var a = 30;
      return this.a;
   }
};

console.log(
   foo.bar(),             // 20
   (foo.bar)(),           // 20
   (foo.bar = foo.bar)(), // 10 // 脱离执行环境,this指向全局
   (foo.bar, foo.bar)()   // 10 // 脱离执行环境,this指向全局
   );

image.png