美文网首页
手写函数

手写函数

作者: 小旎子_8327 | 来源:发表于2020-02-05 16:12 被阅读0次

手写new 函数

步骤:
创建一个新对象
新对象的_proto_指向构造函数的prototype
将构造函数的this指向新对象
执行构造函数
返回新对象

function new(func){
  return function(){
      var obj = new Object();
      obj._proto_ = func.prototype;
      func.apply(obj, arguments);
      return obj;
      }
 }
 new(Person)('name', '12');

实现instanceOf

instanceOf判断一个对象是不是某个类型的实例
思路: a instanceof B
检测a的原型链( _proto_)上是否有B.prototype,若有返回true,否则false。

function instanceOf(obj, func){
       var protoObj = obj._proto_;
       while(protoObj){
            if(protoObj === func.prototype){
                 return true;  
           }
           protoObj = protoObj._proto_;
        }
       return false;
}

相关文章

网友评论

      本文标题:手写函数

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