美文网首页
js call apply instanceof 实现原理

js call apply instanceof 实现原理

作者: 冷暖自知_zjz | 来源:发表于2020-02-15 16:41 被阅读0次

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__;  
    }

}

相关文章

网友评论

      本文标题:js call apply instanceof 实现原理

      本文链接:https://www.haomeiwen.com/subject/jqkyfhtx.html