js call apply instanceof 实现原理

call原理

Function.prototype.mycall = function (context) {
  context = context || window;
// this为调用call方法的方法   eg:person.fullName.call(person1);    也就是这里面的fullName方法
  context.fn = this;
  var args = [];
  for(var i = 1, len = arguments.length; i < len; i++) {
    args.push(arguments[i]);
  }
  let result = context.fn(...args);
  delete context.fn;
  return result
}

apply原理

//apply实现原理
Function.prototype.myapply = function (context) {
  context = context || window;
  context.fn = this;
  let result = context.fn(arguments[1]);
  delete context.fn;
  return result
}

instanceof原理

//来源   https://www.cnblogs.com/mengfangui/p/10220906.html
//示例: a instanceof B
//检测a的原型链(__proto__)上是否有B.prototype,若有返回true,否则false。
function instance_of(L, R) {//L 表示左表达式,R 表示右表达式 
    var O = R.prototype;   // 取 R 的显示原型 
    L = L.__proto__;  
    while (true) {    
        if (L === null)      
             return false;   
        if (O === L)  // 当 O 显式原型 严格等于  L隐式原型 时,返回true
             return true;   
        L = L.__proto__;  
    }

}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。